vue实现批量上传
批量上传的实现方法
在Vue中实现批量上传功能通常需要结合文件选择、预览、上传逻辑以及进度显示等功能。以下是常见的实现方式:
使用input元素选择文件
创建带有multiple属性的文件输入框,允许用户选择多个文件:
<input type="file" multiple @change="handleFileChange" />
在Vue组件中处理文件选择事件:
methods: {
handleFileChange(event) {
const files = event.target.files;
this.selectedFiles = Array.from(files);
}
}
文件预览功能
在提交前显示已选择的文件列表:
<ul>
<li v-for="(file, index) in selectedFiles" :key="index">
{{ file.name }} - {{ (file.size / 1024).toFixed(2) }}KB
<button @click="removeFile(index)">删除</button>
</li>
</ul>
实现上传逻辑
使用FormData对象和axios进行批量上传:
async uploadFiles() {
const formData = new FormData();
this.selectedFiles.forEach(file => {
formData.append('files[]', file);
});
try {
const response = await axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress: progressEvent => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
this.uploadProgress = percentCompleted;
}
});
console.log('上传成功', response.data);
} catch (error) {
console.error('上传失败', error);
}
}
进度显示
在上传过程中显示进度条:
<div v-if="uploadProgress > 0">
<progress :value="uploadProgress" max="100"></progress>
{{ uploadProgress }}%
</div>
拖放上传支持
增强用户体验,支持拖放文件上传:
<div
@dragover.prevent="dragOver"
@dragleave="dragLeave"
@drop.prevent="handleDrop"
:class="{ 'drag-active': isDragActive }"
>
拖放文件到这里
</div>
methods: {
dragOver() {
this.isDragActive = true;
},
dragLeave() {
this.isDragActive = false;
},
handleDrop(event) {
this.isDragActive = false;
const files = event.dataTransfer.files;
this.selectedFiles = Array.from(files);
}
}
文件验证
在上传前验证文件类型和大小:
validateFiles() {
const maxSize = 10 * 1024 * 1024; // 10MB
const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
return this.selectedFiles.every(file => {
return (
allowedTypes.includes(file.type) &&
file.size <= maxSize
);
});
}
分片上传处理大文件
对于大文件,可以考虑分片上传:
async uploadChunks(file) {
const chunkSize = 5 * 1024 * 1024; // 5MB
const chunks = Math.ceil(file.size / chunkSize);
for (let i = 0; i < chunks; i++) {
const start = i * chunkSize;
const end = Math.min(start + chunkSize, file.size);
const chunk = file.slice(start, end);
const formData = new FormData();
formData.append('chunk', chunk);
formData.append('chunkIndex', i);
formData.append('totalChunks', chunks);
formData.append('filename', file.name);
await axios.post('/api/upload-chunk', formData);
this.chunkProgress = Math.round(((i + 1) / chunks) * 100);
}
}
错误处理和重试机制
实现上传失败时的重试逻辑:
async uploadWithRetry(file, retries = 3) {
try {
return await this.uploadFile(file);
} catch (error) {
if (retries > 0) {
return this.uploadWithRetry(file, retries - 1);
}
throw error;
}
}
服务器端响应处理
处理服务器返回的上传结果:
async handleUploadResponse(response) {
if (response.data.success) {
this.uploadedFiles = this.uploadedFiles.concat(response.data.files);
this.selectedFiles = [];
} else {
this.uploadErrors = response.data.errors;
}
}
这些方法组合起来可以构建一个完整的批量上传解决方案,根据实际需求可以选择实现全部或部分功能。







