element中el-upload

<el-upload class="avatar-uploader" ref="uploadImg" action list-type="picture-card" :http-request="uploadImg"
:before-upload="beforeUploadImg" :on-remove="removeImg">
<img v-if="addForm.cover" :src="global.baseURL + addForm.cover" class="avatar g-h100 g-w100" />
<i v-else class="el-icon-plus avatar-uploader-icon g-w100 g-h100"></i>
</el-upload>

//图片提交验证
beforeUploadImg(file) {
const isJPG = file.type === "image/jpg";
const isJPEG = file.type === "image/jpeg";
const isPNG = file.type === "image/png";
const isGIF = file.type === "image/gif";
const isBMP = file.type === "image/bmp";
if (!isJPG && !isJPEG && !isPNG && !isGIF && !isBMP) {
this.$message.error("只能上传图片格式为jpg,jpeg,png,gif,bmp!");
}
return isJPG || isJPEG || isPNG || isGIF || isBMP;

// let files = file.name;
// let suffix = files.substring(files.lastIndexOf(".") + 1, files.length);
// let filetype = ["bmp", "jpg", "jpeg", "png", "gif", "mp4", "avi", "mov", "wmv", "asf", "navi", "3gp", "mkv", "flv",
// "rmvb", "docx", "doc", "xls", "xlxs", "pptx", "pdf", "zip"
// ];
// if (filetype.indexOf(suffix) == -1) {
// this.$message.error("只能上传图片、视频、文档或者压缩包!");
// this.isdel = false;
// }

//return filetype.indexOf(suffix) != -1;

},

//点击图片上传
uploadImg(file) {
this.file = file.file;
},
removeImg(file) {
this.file = "";
},

//表单提交
submitForm() {
this.$refs.addForm.validate(valid => {
if (valid) {
//验证成功执行
let that = this;

this.formData = new FormData();
this.formData.append("file", this.file);

let config = {
//添加请求头
headers: {
"Content-Type": "multipart/form-data"
}
};
axios
.post("xxx", this.formData, config)
.then(function(response) {
if (response.data.success) {
that.$message({
message: "发布成功!",
type: "success"
});
} else {
that.$message.error(response.data.msg);
}
})
.catch(function(err) {
console.log(err);
});
} else {
//定位错误位置
setTimeout(() => {
var isError = document.getElementsByClassName("is-error");
isError[0].querySelector("input").focus();
}, 100);
return false;
}
});
},

原文地址:https://www.cnblogs.com/yyjspace/p/11608131.html