最近在写一个图片上传的功能,不仅要上传,还要进行缩放,并且对图片格式大小进行验证:
<el-upload
action="https://smb-test.cochat.lenovo.com/attachment-server/upload"
:show-file-list="false"
accept=".jpg, .jpeg, .png"
list-type="picture-card"
:on-preview="handlePreview"
:on-progress="imageUploadProgress"
:on-error="imageUploadError"
:on-success="imageUploadSuccess"
:before-upload="beforePicUpload"
v-model="ruleForm.imageUrl"
>
<div v-if="ruleForm.imageUrl" class="bessnessPic">
<img :src="ruleForm.imageUrl" />
</div>
<div v-else class="iconBox">
<i class="el-icon-plus"></i>
<span>点击上传</span>
</div>
</el-upload>
ruleForm: {
imageUrl: '', // 上传的证件图片
},
handlePreview (file) {
// console.log(file + "file.response 可以获得服务端的返回数据");
},
// 上传成功
imageUploadSuccess (response, file) {
if (response.success === true) {
this.ruleForm.imageUrl = response.httpUrl
this.changeTip({
text: '上传成功',
color: true
})
}
// this.ruleForm.imageUrl = URL.createObjectURL(file.raw);
},
// 上传过程
imageUploadProgress (event, file, fileList) {
// console.log("文件上传时的钩子");
},
// 上传失败
imageUploadError (err, file, fileList) {
if (err) {
console.log(err.stack)
}
this.changeTip({
text: '图片过大,上传失败',
color: false
})
},
// 放大图片
handlePictureCardPreview (file) {
this.dialogVisible = true
},
// 上传图片之前检验图片
beforePicUpload (file) {
const isJPG =
file.type === 'image/jpeg' ||
file.type === 'image/jpg' ||
file.type === 'image/png'
const isLt8M = file.size / 1024 / 1024 < 8
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG/JPEG/PNG 格式!')
}
if (!isLt8M) {
this.$message.error('上传头像图片大小不能超过 8MB!')
}
return isJPG && isLt8M
}
欢迎吐槽