Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <template>
- <div>
- <input type="file" @change="onFileSelected">
- <button @click="uploadFile">Upload</button>
- </div>
- </template>
- <script>
- export default {
- data() {
- return {
- file: null,
- fileSize: null,
- chunkSize: 1024 * 1024, // Ukuran chunk dalam byte (1MB)
- uploadedChunks: [],
- totalChunks: null,
- uploadUrl: 'https://example.com/upload'
- }
- },
- methods: {
- onFileSelected(event) {
- this.file = event.target.files[0];
- this.fileSize = this.file.size;
- this.totalChunks = Math.ceil(this.fileSize / this.chunkSize);
- },
- async uploadFile() {
- try {
- const start = performance.now();
- // Membuat Promise untuk tiap chunk
- const chunkPromises = [];
- for (let i = 0; i < this.totalChunks; i++) {
- const startByte = i * this.chunkSize;
- const endByte = Math.min(startByte + this.chunkSize, this.fileSize);
- const chunk = this.file.slice(startByte, endByte);
- const chunkPromise = this.uploadChunk(chunk, i + 1, this.totalChunks);
- chunkPromises.push(chunkPromise);
- }
- // Menunggu semua Promise selesai dijalankan
- await Promise.all(chunkPromises);
- const end = performance.now();
- console.log(`Upload file selesai dalam ${end - start}ms`);
- } catch (error) {
- console.error(error);
- }
- },
- async uploadChunk(chunk, chunkNumber, totalChunks) {
- const formData = new FormData();
- formData.append('file', chunk);
- formData.append('chunkNumber', chunkNumber);
- formData.append('totalChunks', totalChunks);
- const response = await fetch(this.uploadUrl, {
- method: 'POST',
- body: formData
- });
- const result = await response.json();
- this.uploadedChunks.push(chunkNumber);
- console.log(`Chunk ${chunkNumber} berhasil di-upload.`);
- }
- }
- }
- </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement