vue 实现图片上传
使用 Vue 实现图片上传
基础实现(基于 <input type="file">)
-
模板部分
添加文件选择输入框和预览区域:<template> <div> <input type="file" @change="handleFileUpload" accept="image/*" /> <img v-if="imageUrl" :src="imageUrl" alt="Preview" style="max-width: 300px" /> </div> </template> -
逻辑部分
通过FileReader实现本地预览:<script> export default { data() { return { imageUrl: null, selectedFile: null }; }, methods: { handleFileUpload(event) { const file = event.target.files[0]; if (file) { this.selectedFile = file; const reader = new FileReader(); reader.onload = (e) => { this.imageUrl = e.target.result; }; reader.readAsDataURL(file); } } } }; </script>
上传到服务器(Axios 示例)
-
安装 Axios

npm install axios -
添加上传方法
在methods中扩展:async uploadImage() { if (!this.selectedFile) return; const formData = new FormData(); formData.append('image', this.selectedFile); try { const response = await axios.post('/api/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }); console.log('上传成功:', response.data); } catch (error) { console.error('上传失败:', error); } }
使用第三方库(如 vue-dropzone)
-
安装依赖

npm install vue2-dropzone -
组件集成
<template> <vue-dropzone ref="dropzone" id="dropzone" :options="dropzoneOptions" @vdropzone-success="uploadSuccess" /> </template> <script> import vue2Dropzone from 'vue2-dropzone'; export default { components: { vueDropzone: vue2Dropzone }, data() { return { dropzoneOptions: { url: '/api/upload', thumbnailWidth: 200, maxFilesize: 2, // MB acceptedFiles: 'image/*' } }; }, methods: { uploadSuccess(file, response) { console.log('文件上传成功', response); } } }; </script>
验证与限制
-
文件类型验证
在handleFileUpload方法中添加:if (!file.type.match('image.*')) { alert('请选择图片文件'); return; } -
文件大小限制
const maxSize = 2 * 1024 * 1024; // 2MB if (file.size > maxSize) { alert('文件大小超过限制'); return; }
进度显示(Axios)
const response = await axios.post('/api/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: (progressEvent) => {
const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
console.log(`上传进度: ${percent}%`);
}
});
注意事项
- 后端需支持
multipart/form-data格式接收文件。 - 生产环境需添加更完善的错误处理(如网络异常、服务器错误等)。
- 如需多图上传,可扩展为
<input type="file" multiple>并遍历event.target.files。






