vue上传图片实现
使用 <input type="file"> 获取文件
创建文件上传输入框,通过 @change 事件监听文件选择:
<template>
<input type="file" accept="image/*" @change="handleFileUpload" />
</template>
accept="image/*" 限制只能选择图片文件。
通过 FormData 上传文件
在 handleFileUpload 方法中,将文件添加到 FormData 对象并发送到服务器:
methods: {
handleFileUpload(event) {
const file = event.target.files[0];
const formData = new FormData();
formData.append('image', file);
axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
console.log('上传成功', response.data);
}).catch(error => {
console.error('上传失败', error);
});
}
}
Content-Type: multipart/form-data 是文件上传必需的请求头。
显示预览图片
通过 URL.createObjectURL 生成临时链接实现前端预览:
<template>
<img v-if="previewUrl" :src="previewUrl" alt="预览" style="max-width: 200px;" />
</template>
<script>
export default {
data() {
return {
previewUrl: null
};
},
methods: {
handleFileUpload(event) {
const file = event.target.files[0];
this.previewUrl = URL.createObjectURL(file);
// 上传逻辑...
}
},
beforeUnmount() {
if (this.previewUrl) URL.revokeObjectURL(this.previewUrl);
}
};
</script>
组件销毁时需调用 URL.revokeObjectURL 释放内存。
多文件上传支持
修改 @change 事件处理逻辑以支持多文件:
handleFileUpload(event) {
const files = Array.from(event.target.files);
const formData = new FormData();
files.forEach(file => {
formData.append('images[]', file); // 注意字段名带[]表示数组
});
// 后续上传逻辑相同...
}
HTML 需添加 multiple 属性:
<input type="file" accept="image/*" multiple @change="handleFileUpload" />
文件类型和大小验证
在上传前添加验证逻辑:
handleFileUpload(event) {
const file = event.target.files[0];
const validTypes = ['image/jpeg', 'image/png'];
const maxSize = 2 * 1024 * 1024; // 2MB
if (!validTypes.includes(file.type)) {
alert('仅支持JPEG/PNG格式');
return;
}
if (file.size > maxSize) {
alert('文件大小不能超过2MB');
return;
}
// 验证通过后执行上传...
}
可根据需求调整文件类型和大小限制。
进度条显示
利用 Axios 的 onUploadProgress 实现上传进度显示:
<template>
<progress :value="uploadProgress" max="100"></progress>
</template>
<script>
export default {
data() {
return {
uploadProgress: 0
};
},
methods: {
handleFileUpload(event) {
const config = {
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: progressEvent => {
this.uploadProgress = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
}
};
axios.post('/api/upload', formData, config).then(...);
}
}
};
</script>
进度计算基于已上传字节与总字节的比例。







