vue实现文件上传前端
使用 Vue 实现文件上传前端
安装依赖
在项目中安装 axios 用于发送文件上传请求:
npm install axios
创建文件上传组件 创建一个 Vue 组件,包含文件选择输入和上传按钮:

<template>
<div>
<input type="file" @change="handleFileChange" />
<button @click="uploadFile">上传文件</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
file: null
};
},
methods: {
handleFileChange(event) {
this.file = event.target.files[0];
},
uploadFile() {
if (!this.file) {
alert('请选择文件');
return;
}
const formData = new FormData();
formData.append('file', this.file);
axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
alert('上传成功');
}).catch(error => {
alert('上传失败');
});
}
}
};
</script>
处理多文件上传
如果需要支持多文件上传,修改 handleFileChange 方法:
handleFileChange(event) {
this.files = event.target.files;
},
uploadFiles() {
const formData = new FormData();
Array.from(this.files).forEach(file => {
formData.append('files', file);
});
axios.post('/api/upload-multiple', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
}
显示上传进度 添加进度条显示上传进度:

<template>
<div>
<input type="file" @change="handleFileChange" />
<button @click="uploadFile">上传文件</button>
<progress :value="progress" max="100"></progress>
</div>
</template>
<script>
export default {
data() {
return {
progress: 0
};
},
methods: {
uploadFile() {
const config = {
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress: progressEvent => {
this.progress = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
}
};
axios.post('/api/upload', formData, config)
}
}
};
</script>
文件类型和大小验证 在上传前验证文件类型和大小:
uploadFile() {
const allowedTypes = ['image/jpeg', 'image/png'];
const maxSize = 2 * 1024 * 1024; // 2MB
if (!allowedTypes.includes(this.file.type)) {
alert('仅支持JPEG和PNG格式');
return;
}
if (this.file.size > maxSize) {
alert('文件大小不能超过2MB');
return;
}
// 上传逻辑
}
使用第三方库
考虑使用 vue-upload-component 等第三方库简化实现:
npm install vue-upload-component
<template>
<file-upload
url="/api/upload"
@input-file="inputFile"
@input-filter="inputFilter"
></file-upload>
</template>
<script>
import FileUpload from 'vue-upload-component';
export default {
components: {
FileUpload
},
methods: {
inputFile(newFile, oldFile) {
// 文件选择回调
},
inputFilter(newFile, oldFile, prevent) {
// 文件过滤
}
}
};
</script>






