在vue项目中,有上传图片的需求时,先进行本地存储,等最后确定提交后,调用接口时再进行真正上传图片,可以减小服务器压力,减少占用空间,以避免多次重复上传。
示例为:
1、仅可上传一张图片
2、图片限制:只能上传jpg/png文件,且不超过2MB
<el-upload
action="#"
accept=".jpg, .png"
:multiple="false"
ref="uploadImg"
:auto-upload="false"
list-type="picture-card"
:on-change="handleFileChange"
:on-remove="handleRemove"
:limit="1">
<i slot="default" class="el-icon-plus"></i>
<div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过2MB</div>
</el-upload>
import axios from "axios";
handleFileChange(file, fileList) {
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
this.$message({
message:"上传图片大小不能超过2MB!",
type: 'warning'
});
this.$refs.uploadImg.clearFiles();
}else{
this.form.file = file.raw;
this.invoicePicture = false;
document.body.querySelector('.el-upload--picture-card').style.display = 'none';
}
},
handleRemove(file) {
this.form.file = null;
this.invoicePicture = true;
document.body.querySelector('.el-upload--picture-card').style.display = '';
},
submitForm(){
var formData = new FormData();
formData.append("file", this.form.file);
let config = {
headers: {
"Content-Type": "multipart/form-data"
}
};
axios
.post(accountDetailedProcessBacklog, formData, config)
.then(res => {
if (res.data.data.status == 1) {
this.$message({
message:`${this.action}成功`,
type: 'success'
});
}else{
this.$message({
message:res.data.data.msg,
type: 'error'
});
}
})
.catch(err => {});
}