vue实现上传功能
使用 Vue 实现文件上传功能
Vue 可以通过原生 HTML 的 <input type="file"> 结合 Vue 的数据绑定和方法实现文件上传功能。以下是具体实现方式:
基础文件上传实现
创建一个文件输入框并绑定 change 事件:
<template>
<div>
<input type="file" @change="handleFileUpload" />
<button @click="submitFile">上传</button>
</div>
</template>
<script>
export default {
data() {
return {
file: null
}
},
methods: {
handleFileUpload(event) {
this.file = event.target.files[0]
},
submitFile() {
if (!this.file) return
const formData = new FormData()
formData.append('file', this.file)
// 这里使用 axios 发送请求
axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
console.log('上传成功', response)
}).catch(error => {
console.error('上传失败', error)
})
}
}
}
</script>
多文件上传实现
修改 handleFileUpload 方法以支持多文件选择:
handleFileUpload(event) {
this.files = Array.from(event.target.files)
},
submitFiles() {
const formData = new FormData()
this.files.forEach(file => {
formData.append('files[]', file)
})
axios.post('/multi-upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
}
上传进度显示
添加上传进度监控:
axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress: progressEvent => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
)
console.log(percentCompleted + '%')
// 可以绑定到 data 中的 progress 变量显示进度条
}
})
使用第三方库
对于更复杂的需求,可以考虑使用专门的上传组件库:
- vue-upload-component
- vue-dropzone
- element-ui 的 upload 组件
例如使用 element-ui:
<el-upload
action="/upload"
:on-success="handleSuccess"
:before-upload="beforeUpload">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
文件验证
在上传前进行文件验证:
beforeUpload(file) {
const isJPG = file.type === 'image/jpeg'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isJPG) {
console.error('只能上传 JPG 格式图片!')
return false
}
if (!isLt2M) {
console.error('图片大小不能超过 2MB!')
return false
}
return true
}
这些方法涵盖了从基础到进阶的文件上传实现,可以根据项目需求选择适合的方式。







