vue上传文件实现导入
文件上传基础实现
使用Vue实现文件上传可以通过<input type="file">元素结合FormData对象完成。以下是基本实现方式:
<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]
},
async submitFile() {
if (!this.file) return
const formData = new FormData()
formData.append('file', this.file)
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>
多文件上传支持
需要上传多个文件时,可以修改文件选择处理逻辑:
handleFileUpload(event) {
this.files = Array.from(event.target.files)
},
async submitFiles() {
if (!this.files.length) return
const formData = new FormData()
this.files.forEach(file => {
formData.append('files[]', file)
})
// 其余上传逻辑相同
}
进度显示实现
添加上传进度显示功能:
async submitFile() {
const config = {
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: progressEvent => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
)
this.uploadProgress = percentCompleted
}
}
await axios.post('/api/upload', formData, config)
}
文件类型和大小限制
在客户端添加文件验证:
handleFileUpload(event) {
const file = event.target.files[0]
const validTypes = ['image/jpeg', 'image/png']
const maxSize = 5 * 1024 * 1024 // 5MB
if (!validTypes.includes(file.type)) {
alert('仅支持JPEG/PNG格式')
return
}
if (file.size > maxSize) {
alert('文件大小不能超过5MB')
return
}
this.file = file
}
第三方库使用
使用vue-dropzone等第三方组件可以简化实现:
import vue2Dropzone from 'vue2-dropzone'
export default {
components: {
vueDropzone: vue2Dropzone
},
data() {
return {
dropzoneOptions: {
url: '/api/upload',
maxFilesize: 5, // MB
acceptedFiles: 'image/*',
addRemoveLinks: true
}
}
}
}
<vue-dropzone
id="dropzone"
:options="dropzoneOptions"
@vdropzone-success="uploadSuccess"
></vue-dropzone>
服务器端配合
Node.js Express处理上传示例:
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
app.post('/api/upload', upload.single('file'), (req, res) => {
// req.file包含上传文件信息
res.json({ message: '上传成功', file: req.file })
})






