vue 实现上传图片
使用 <input type="file"> 实现基础上传
通过 HTML 原生文件选择控件获取图片文件,结合 Vue 处理文件选择和预览:
<template>
<div>
<input type="file" @change="handleFileChange" accept="image/*">
<img v-if="imageUrl" :src="imageUrl" width="200">
</div>
</template>
<script>
export default {
data() {
return {
imageUrl: null
}
},
methods: {
handleFileChange(e) {
const file = e.target.files[0];
if (file) {
this.imageUrl = URL.createObjectURL(file);
// 此处可添加上传逻辑
}
}
}
}
</script>
使用 axios 提交文件到服务器
通过 FormData 对象封装文件数据,配合 axios 发送到后端接口:
methods: {
async uploadFile(file) {
const formData = new FormData();
formData.append('image', file);
try {
const response = await axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
console.log('上传成功:', response.data);
} catch (error) {
console.error('上传失败:', error);
}
}
}
拖拽上传实现
添加拖拽区域监听 dragover 和 drop 事件,提升用户体验:
<template>
<div
@dragover.prevent="dragover"
@drop.prevent="drop"
class="drop-zone"
>
拖拽图片到此处
</div>
</template>
<script>
export default {
methods: {
dragover(e) {
e.target.classList.add('bg-blue-100');
},
drop(e) {
e.target.classList.remove('bg-blue-100');
const file = e.dataTransfer.files[0];
if (file && file.type.match('image.*')) {
this.handleFileUpload(file);
}
}
}
}
</script>
图片压缩与格式转换
使用 canvas 实现客户端图片压缩,减少上传体积:
compressImage(file, quality = 0.8) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = img.width * 0.5;
canvas.height = img.height * 0.5;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
canvas.toBlob(resolve, 'image/jpeg', quality);
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
});
}
第三方库集成(如 vue-dropzone)
快速实现高级上传功能(分块上传、进度显示等):
npm install vue2-dropzone
<template>
<vue-dropzone
ref="dropzone"
id="custom-dropzone"
:options="dropzoneOptions"
@vdropzone-success="uploadSuccess"
></vue-dropzone>
</template>
<script>
import vue2Dropzone from 'vue2-dropzone';
export default {
components: { vueDropzone: vue2Dropzone },
data() {
return {
dropzoneOptions: {
url: '/api/upload',
thumbnailWidth: 200,
maxFilesize: 10 // MB
}
}
}
}
</script>
注意事项
- 文件类型验证需检查
file.type或文件扩展名 - 移动端需处理
accept="image/*"的兼容性问题 - 大文件上传建议实现分片(chunk)上传逻辑
- 服务端需配置 CORS 和文件大小限制







