vue实现文档上传
Vue 实现文档上传的方法
使用原生 HTML 表单和 Vue 结合
在 Vue 组件中创建一个表单,利用 HTML 的 input 元素设置 type="file" 来允许用户选择文件。通过 Vue 的 v-on 指令监听文件选择事件。
<template>
<div>
<input type="file" @change="handleFileUpload" />
<button @click="uploadFile">上传文件</button>
</div>
</template>
<script>
export default {
methods: {
handleFileUpload(event) {
this.selectedFile = event.target.files[0];
},
uploadFile() {
if (!this.selectedFile) return;
const formData = new FormData();
formData.append('file', this.selectedFile);
// 使用 axios 或其他 HTTP 客户端发送请求
axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
console.log('上传成功', response.data);
}).catch(error => {
console.error('上传失败', error);
});
}
},
data() {
return {
selectedFile: null
};
}
};
</script>
使用第三方库(如 Vue-Dropzone)
如果需要更丰富的上传功能(如拖拽上传、预览等),可以使用第三方库如 vue-dropzone。
安装依赖:

npm install vue2-dropzone
在 Vue 组件中使用:
<template>
<div>
<vue-dropzone
ref="myVueDropzone"
id="dropzone"
:options="dropzoneOptions"
@vdropzone-success="uploadSuccess"
></vue-dropzone>
</div>
</template>
<script>
import vue2Dropzone from 'vue2-dropzone';
import 'vue2-dropzone/dist/vue2Dropzone.min.css';
export default {
components: {
vueDropzone: vue2Dropzone
},
data() {
return {
dropzoneOptions: {
url: '/api/upload',
thumbnailWidth: 150,
maxFilesize: 2, // MB
headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') }
}
};
},
methods: {
uploadSuccess(file, response) {
console.log('文件上传成功', response);
}
}
};
</script>
文件上传前的验证
可以在上传前对文件大小、类型等进行验证:

methods: {
handleFileUpload(event) {
const file = event.target.files[0];
const allowedTypes = ['application/pdf', 'image/jpeg', 'image/png'];
const maxSize = 2 * 1024 * 1024; // 2MB
if (!allowedTypes.includes(file.type)) {
alert('请上传 PDF、JPEG 或 PNG 文件');
return;
}
if (file.size > maxSize) {
alert('文件大小不能超过 2MB');
return;
}
this.selectedFile = file;
}
}
显示上传进度
如果需要显示上传进度,可以通过 axios 的 onUploadProgress 实现:
uploadFile() {
const formData = new FormData();
formData.append('file', this.selectedFile);
axios.post('/api/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: progressEvent => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
console.log(percentCompleted + '%');
}
}).then(response => {
console.log('上传完成', response.data);
});
}
多文件上传
支持多文件上传时,需将 input 的 multiple 属性设置为 true,并调整数据处理逻辑:
<input type="file" multiple @change="handleFileUpload" />
handleFileUpload(event) {
this.selectedFiles = Array.from(event.target.files);
},
uploadFiles() {
const formData = new FormData();
this.selectedFiles.forEach(file => {
formData.append('files[]', file);
});
axios.post('/api/upload-multiple', formData);
}






