html部分(此处使用了element-ui的图片上传组件)
<el-upload :action="Api" list-type="picture-card" :before-upload="beforeUpload"></el-upload>
js部分
/* 限制图片上传 */
beforeUpload(file) {
let _this = this
let suffix = _this.getFileType(file.name) //获取文件后缀名
let suffixArray = ['jpg', 'png', 'jpeg', 'gif', 'jfif'] //限制的文件类型
let limitWidth = 1280 //默认文件宽度
if (suffixArray.indexOf(suffix) === -1) {
_this.$message({
message: '只允许上传图片',
type: 'error',
duration: this.elDuration
})
}
return new Promise((resolve, reject) => {
// let isLt10M = file.size / 1024 / 1024 < 10 // 判定图片大小是否小于10MB
// if (!isLt10M) {
// reject()
// }
let image = new Image(),
resultBlob = '';
image.src = URL.createObjectURL(file);
image.onload = () => {
// 调用方法获取blob格式
resultBlob = _this.compressUpload(image, file, limitWidth);
resolve(resultBlob)
}
image.onerror = () => {
reject()
}
})
},
compressUpload(image, file, limitWidth) {
let canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d')
// 获取原图比例
let {
width,
height
} = image
let scale = width / height; //图片比例
let ctxHeight = limitWidth / scale; //图片高度
// 创建属性节点
let nodeWidth = document.createAttribute("width");
nodeWidth.nodeValue = limitWidth;
let nodeHeight = document.createAttribute("height");
nodeHeight.nodeValue = ctxHeight;
canvas.setAttributeNode(nodeWidth);
canvas.setAttributeNode(nodeHeight);
ctx.drawImage(image, 0, 0, limitWidth, ctxHeight)
// 进行压缩
let compressData = canvas.toDataURL(file.type || 'image/jpeg', 1.0)
// 压缩后进行base64转Blob
let byteString;
if (compressData.split(',')[0].indexOf('base64') >= 0) {
byteString = atob(compressData.split(',')[1])
} else {
byteString = unescape(compressData.split(',')[1])
}
let mimeString = compressData.split(',')[0].split(':')[1].split(';')[0];
let ia = new Uint8Array(byteString.length)
for (let i = 0; i < byteString.length; i += 1) {
ia[i] = byteString.charCodeAt(i)
}
let blobImg = new Blob([ia], {
type: mimeString
})
return blobImg
},