vue实现图片的上传
基础实现方法
使用<input type="file">元素结合FormData实现图片上传
<template>
<div>
<input type="file" @change="handleFileChange" accept="image/*">
<button @click="uploadImage">上传图片</button>
<img v-if="imageUrl" :src="imageUrl" alt="预览">
</div>
</template>
<script>
export default {
data() {
return {
selectedFile: null,
imageUrl: ''
}
},
methods: {
handleFileChange(event) {
this.selectedFile = event.target.files[0]
this.imageUrl = URL.createObjectURL(this.selectedFile)
},
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)
}
}
}
}
</script>
使用第三方库优化
安装vue-upload-component简化上传流程
npm install vue-upload-component
组件实现示例
<template>
<file-upload
ref="upload"
v-model="files"
post-action="/api/upload"
put-action="/api/upload"
@input-file="inputFile"
@input-filter="inputFilter">
<button>选择文件</button>
</file-upload>
</template>
<script>
import FileUpload from 'vue-upload-component'
export default {
components: {
FileUpload
},
data() {
return {
files: []
}
},
methods: {
inputFile(newFile, oldFile) {
if (newFile && !oldFile) {
// 添加新文件
}
if (newFile && oldFile) {
// 更新文件
}
if (!newFile && oldFile) {
// 删除文件
}
},
inputFilter(newFile, oldFile, prevent) {
if (newFile && !oldFile) {
// 过滤非图片文件
if (!/\.(jpe?g|png|gif)$/i.test(newFile.name)) {
return prevent()
}
}
}
}
}
</script>
图片压缩处理
使用compressorjs实现客户端图片压缩

npm install compressorjs
压缩后上传实现
import Compressor from 'compressorjs'
methods: {
async uploadWithCompression() {
new Compressor(this.selectedFile, {
quality: 0.6,
success: async (result) => {
const formData = new FormData()
formData.append('image', result, result.name)
try {
const response = await axios.post('/api/upload', formData)
console.log('压缩上传成功:', response.data)
} catch (error) {
console.error('上传失败:', error)
}
},
error(err) {
console.error('压缩失败:', err)
}
})
}
}
多图上传实现
支持多文件选择和上传

<input type="file" multiple @change="handleMultiFileChange" accept="image/*">
数据处理方法
methods: {
handleMultiFileChange(event) {
this.selectedFiles = Array.from(event.target.files)
this.imagePreviews = this.selectedFiles.map(file => URL.createObjectURL(file))
},
async uploadMultiple() {
if (!this.selectedFiles.length) return
const formData = new FormData()
this.selectedFiles.forEach((file, index) => {
formData.append(`images[${index}]`, file)
})
try {
const response = await axios.post('/api/multi-upload', formData)
console.log('多图上传成功:', response.data)
} catch (error) {
console.error('上传失败:', error)
}
}
}
进度显示实现
显示上传进度条
<progress :value="uploadProgress" max="100"></progress>
<span>{{ uploadProgress }}%</span>
进度监控实现
methods: {
async uploadWithProgress() {
const config = {
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: progressEvent => {
this.uploadProgress = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
)
}
}
try {
const response = await axios.post('/api/upload', formData, config)
console.log('上传完成:', response.data)
} catch (error) {
console.error('上传失败:', error)
}
}
}






