Element UI 图片上传,前端控制宽高
<div>
<!-- <input
v-model="postModel.title_img"
type="text"
class="allInput"
/> -->
<el-upload
class="images-uploader"
action="#"
:http-request="handelImageRequest"
:show-file-list="false"
:before-upload="beforeImagesUpload"
:auto-upload="true"
>
<img
v-if="postModel.title_img"
:src="postModel.title_img"
class="images"
/>
<i v-else class="el-icon-plus images-uploader-icon"></i>
</el-upload>
</div>
beforeImagesUpload(file) {
const ext = file.type.split('/')[1];
const isImg = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(ext.toLowerCase()) !== -1;
const isLt2M = file.size / 1024 / 1024 < 1;
if (!isImg) {
this.$message.error("请上传正确的图片文件!");
}
if (!isLt2M) {
this.$message.error("图片大小不能超过1MB!");
}
return isImg && isLt2M;
},
handelImageRequest(param) {
const formData = new FormData()
formData.append('file', param.file)
let config = {
headers:{"Content-Type":"multipart/form-data"}
};
let that = this;
this.$axios.post("/Upload/getImgUrl", formData , config ).then((p) => {
// console.log(p); // 直接返回图片地址
that.postModel.title_img = p;
});
}
<style scoped>
.images-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.images-uploader .el-upload:hover {
border-color: #409eff;
}
.images-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
border:1px dashed #8c939d;
}
.images {
width: 178px;
height: 178px;
display: block;
}
</style>
控制宽高
validWidth:200,
validHeight:200
beforeImagesUpload(file) {
const ext = file.type.split("/")[1];
const isImg =
[
"png",
"jpg",
"jpeg",
"bmp",
"gif",
"webp",
"psd",
"svg",
"tiff",
].indexOf(ext.toLowerCase()) !== -1;
const isLt2M = file.size / 1024 / 1024 < 1;
if (!isImg) {
this.$message.error("请上传正确的图片文件!");
}
if (!isLt2M) {
this.$message.error("图片大小不能超过1MB!");
}
// 验证图片宽高
let isWHValid = true;
if (this.validWidth && this.validHeight) {
isWHValid = this.valWidthAndHeight(file);
}
return isImg && isLt2M && isWHValid;
},
handelImageRequest(param) {
const formData = new FormData();
formData.append("file", param.file);
let config = {
headers: { "Content-Type": "multipart/form-data" },
};
let that = this;
this.$axios.post("/Upload/getImgUrl", formData, config).then((p) => {
// console.log(p); // 直接返回图片地址
that.postModel.title_img = p;
});
},
//验证图片宽高
valWidthAndHeight: function (file) {
let _this = this;
return new Promise(function (resolve, reject) {
let width = _this.validWidth; //图片宽度
let height = _this.validHeight; //图片高度
let _URL = window.URL || window.webkitURL;
let image = new Image();
image.src = _URL.createObjectURL(file);
image.onload = function () {
let valid = image.width == width && image.height == height;
valid ? resolve() : reject();
};
}).then(
() => {
return file;
},
() => {
this.$message.error(
"上传图片尺寸不符合,只能是" +
_this.validWidth +
"*" +
_this.validHeight +
"!"
);
return Promise.reject();
}
);
}