vue图片上传实现
图片上传基础实现
使用Vue结合HTML5的<input type="file">元素实现基础图片上传功能。通过FileReaderAPI预览图片,利用FormData对象处理文件数据。
<template>
<div>
<input type="file" accept="image/*" @change="handleFileChange">
<img v-if="imageUrl" :src="imageUrl" width="200">
<button @click="uploadImage">上传</button>
</div>
</template>
<script>
export default {
data() {
return {
selectedFile: null,
imageUrl: ''
}
},
methods: {
handleFileChange(e) {
const file = e.target.files[0]
if (file) {
this.selectedFile = file
const reader = new FileReader()
reader.onload = (e) => {
this.imageUrl = e.target.result
}
reader.readAsDataURL(file)
}
},
uploadImage() {
if (!this.selectedFile) return
const formData = new FormData()
formData.append('image', this.selectedFile)
// 替换为实际API端点
axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
console.log('上传成功', response.data)
}).catch(error => {
console.error('上传失败', error)
})
}
}
}
</script>
多文件上传处理
扩展基础实现以支持多文件选择和上传,展示预览缩略图列表。

<template>
<div>
<input type="file" multiple accept="image/*" @change="handleFilesChange">
<div v-for="(img, index) in imagePreviews" :key="index">
<img :src="img" width="100">
<button @click="removeImage(index)">删除</button>
</div>
<button @click="uploadAll">上传全部</button>
</div>
</template>
<script>
export default {
data() {
return {
selectedFiles: [],
imagePreviews: []
}
},
methods: {
handleFilesChange(e) {
const files = Array.from(e.target.files)
files.forEach(file => {
const reader = new FileReader()
reader.onload = (e) => {
this.imagePreviews.push(e.target.result)
this.selectedFiles.push(file)
}
reader.readAsDataURL(file)
})
},
removeImage(index) {
this.imagePreviews.splice(index, 1)
this.selectedFiles.splice(index, 1)
},
uploadAll() {
if (this.selectedFiles.length === 0) return
const formData = new FormData()
this.selectedFiles.forEach((file, i) => {
formData.append(`images[${i}]`, file)
})
axios.post('/api/multi-upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
console.log('批量上传成功', response.data)
})
}
}
}
</script>
上传进度显示
集成上传进度指示功能,增强用户体验。
methods: {
uploadWithProgress() {
const formData = new FormData()
formData.append('image', this.selectedFile)
axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress: (progressEvent) => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
)
this.uploadProgress = percentCompleted
}
}).then(response => {
this.uploadProgress = 100
setTimeout(() => {
this.uploadProgress = 0
}, 1000)
})
}
}
文件类型和大小验证
添加前端验证确保上传文件符合要求。

methods: {
validateFile(file) {
const validTypes = ['image/jpeg', 'image/png', 'image/gif']
const maxSize = 2 * 1024 * 1024 // 2MB
if (!validTypes.includes(file.type)) {
alert('仅支持JPEG、PNG、GIF格式')
return false
}
if (file.size > maxSize) {
alert('文件大小不能超过2MB')
return false
}
return true
},
handleFileChange(e) {
const file = e.target.files[0]
if (file && this.validateFile(file)) {
// 处理有效文件
}
}
}
第三方组件集成
推荐使用成熟的第三方Vue组件库实现更丰富的上传功能:
- Element UI的
el-upload组件 - Vuetify的
v-file-input组件 - Ant Design Vue的
a-upload组件
以Element UI为例:
<template>
<el-upload
action="/api/upload"
list-type="picture-card"
:auto-upload="false"
:on-change="handleChange"
:file-list="fileList">
<i class="el-icon-plus"></i>
</el-upload>
</template>
<script>
export default {
data() {
return {
fileList: []
}
},
methods: {
handleChange(file, fileList) {
this.fileList = fileList
}
}
}
</script>






