Advertisement
sugengdcahyo

chunk upload nuxt js

May 3rd, 2023
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.94 KB | Source Code | 0 0
  1. <template>
  2.   <div>
  3.     <input type="file" @change="onFileSelected">
  4.     <button @click="uploadFile">Upload</button>
  5.   </div>
  6. </template>
  7.  
  8. <script>
  9. export default {
  10.   data() {
  11.     return {
  12.       file: null,
  13.       fileSize: null,
  14.       chunkSize: 1024 * 1024, // Ukuran chunk dalam byte (1MB)
  15.       uploadedChunks: [],
  16.       totalChunks: null,
  17.       uploadUrl: 'https://example.com/upload'
  18.     }
  19.   },
  20.   methods: {
  21.     onFileSelected(event) {
  22.       this.file = event.target.files[0];
  23.       this.fileSize = this.file.size;
  24.       this.totalChunks = Math.ceil(this.fileSize / this.chunkSize);
  25.     },
  26.     async uploadFile() {
  27.       try {
  28.         const start = performance.now();
  29.  
  30.         // Membuat Promise untuk tiap chunk
  31.         const chunkPromises = [];
  32.         for (let i = 0; i < this.totalChunks; i++) {
  33.           const startByte = i * this.chunkSize;
  34.           const endByte = Math.min(startByte + this.chunkSize, this.fileSize);
  35.           const chunk = this.file.slice(startByte, endByte);
  36.           const chunkPromise = this.uploadChunk(chunk, i + 1, this.totalChunks);
  37.           chunkPromises.push(chunkPromise);
  38.         }
  39.  
  40.         // Menunggu semua Promise selesai dijalankan
  41.         await Promise.all(chunkPromises);
  42.  
  43.         const end = performance.now();
  44.         console.log(`Upload file selesai dalam ${end - start}ms`);
  45.       } catch (error) {
  46.         console.error(error);
  47.       }
  48.     },
  49.     async uploadChunk(chunk, chunkNumber, totalChunks) {
  50.       const formData = new FormData();
  51.       formData.append('file', chunk);
  52.       formData.append('chunkNumber', chunkNumber);
  53.       formData.append('totalChunks', totalChunks);
  54.  
  55.       const response = await fetch(this.uploadUrl, {
  56.         method: 'POST',
  57.         body: formData
  58.       });
  59.  
  60.       const result = await response.json();
  61.       this.uploadedChunks.push(chunkNumber);
  62.  
  63.       console.log(`Chunk ${chunkNumber} berhasil di-upload.`);
  64.     }
  65.   }
  66. }
  67. </script>
Tags: js nuxt
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement