vue实现图片上传源码
Vue 图片上传实现源码
以下是一个基于 Vue 的图片上传组件实现,包含前端代码和关键逻辑说明。示例使用 axios 发送请求,并支持预览、限制文件类型和大小等功能。
基础模板结构
<template>
<div class="upload-container">
<input
type="file"
accept="image/*"
@change="handleFileChange"
ref="fileInput"
/>
<button @click="triggerUpload">选择图片</button>
<!-- 图片预览 -->
<div v-if="previewUrl" class="preview">
<img :src="previewUrl" alt="预览" />
<button @click="removeImage">删除</button>
</div>
<!-- 上传按钮 -->
<button
@click="uploadImage"
:disabled="!selectedFile"
>上传</button>
<!-- 进度条 -->
<div v-if="uploadProgress > 0" class="progress">
<div :style="{ width: uploadProgress + '%' }"></div>
</div>
</div>
</template>
脚本逻辑
<script>
import axios from 'axios';
export default {
data() {
return {
selectedFile: null,
previewUrl: '',
uploadProgress: 0
};
},
methods: {
triggerUpload() {
this.$refs.fileInput.click();
},
handleFileChange(e) {
const file = e.target.files[0];
if (!file) return;
// 校验文件类型和大小(示例限制2MB)
const validTypes = ['image/jpeg', 'image/png', 'image/gif'];
const maxSize = 2 * 1024 * 1024; // 2MB
if (!validTypes.includes(file.type)) {
alert('仅支持JPEG/PNG/GIF格式');
return;
}
if (file.size > maxSize) {
alert('文件大小不能超过2MB');
return;
}
this.selectedFile = file;
this.previewUrl = URL.createObjectURL(file);
},
removeImage() {
this.selectedFile = null;
this.previewUrl = '';
this.$refs.fileInput.value = '';
},
async uploadImage() {
if (!this.selectedFile) return;
const formData = new FormData();
formData.append('image', this.selectedFile);
try {
const res = await axios.post('/api/upload', formData, {
onUploadProgress: (progressEvent) => {
this.uploadProgress = Math.round(
(progressEvent.loaded / progressEvent.total) * 100
);
}
});
alert('上传成功');
this.$emit('uploaded', res.data.url); // 触发成功回调
this.removeImage();
} catch (error) {
alert('上传失败: ' + error.message);
} finally {
this.uploadProgress = 0;
}
}
}
};
</script>
样式示例
<style scoped>
.upload-container {
display: flex;
flex-direction: column;
gap: 10px;
max-width: 500px;
}
input[type="file"] {
display: none;
}
.preview img {
max-width: 100%;
max-height: 200px;
}
.progress {
height: 6px;
background: #eee;
}
.progress div {
height: 100%;
background: #42b983;
transition: width 0.3s;
}
</style>
关键功能说明
文件选择与预览
通过隐藏的 <input type="file"> 触发文件选择,使用 URL.createObjectURL 生成预览图的临时URL。
文件校验
在 handleFileChange 方法中对文件类型和大小进行校验,避免无效上传。
上传进度
通过 axios 的 onUploadProgress 回调实现实时进度显示,进度条通过CSS动态宽度呈现。

后端对接
示例中上传接口为 /api/upload,实际需替换为真实接口地址。后端需接收 multipart/form-data 格式数据。
扩展建议
-
多图上传
修改input的multiple属性并调整逻辑为数组存储:
<input type="file" multiple @change="handleFilesChange" /> -
拖拽上传
添加拖拽区域事件监听:@dragover.prevent @drop.prevent="handleDrop" -
图片裁剪
集成第三方库如cropperjs实现前端裁剪功能。 -
云存储直传
如需上传至阿里云OSS或七牛云等,可使用各平台提供的SDK实现签名直传。






