<template>
<div>
<input type="file" @change="handleFileChange" />
<button @click="uploadFile">Upload</button>
</div>
</template>
<script>
export default {
data() {
return {
file: null,
chunkSize: 1024 * 1024, // 1MB chunks
totalChunks: 0,
currentChunk: 0,
};
},
methods: {
handleFileChange(event) {
this.file = event.target.files[0];
},
uploadFile() {
this.totalChunks = Math.ceil(this.file.size / this.chunkSize);
this.uploadChunk();
},
uploadChunk() {
const start = this.currentChunk * this.chunkSize;
const end = Math.min((this.currentChunk + 1) * this.chunkSize, this.file.size);
const chunk = this.file.slice(start, end);
// Replace with your backend URL
const uploadUrl = 'http://your-backend-url/upload';
const formData = new FormData();
formData.append('file', chunk);
formData.append('totalChunks', this.totalChunks);
formData.append('currentChunk', this.currentChunk);
fetch(uploadUrl, {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => {
console.log('Chunk uploaded:', data.percent);
this.currentChunk++;
if (this.currentChunk < this.totalChunks) {
this.uploadChunk();
} else {
console.log('File uploaded successfully');
}
})
.catch(error => {
console.error('Error uploading chunk:', error);
});
},
},
};
</script>
vue中大文件分片上传
最新推荐文章于 2024-11-12 20:45:00 发布