由于之前没人维护项目,图片数据库马上就要炸了,今天搞了个上传图片压缩的小功能来缓解以后的压力
使用了EL-UPLOAD来做示例,以及compressorjs处理压缩。
首先安装compressorjs
npm install compressorjs --save
JS部分
在方法中使用了compressImage 方法压缩图片,由于测试没有服务器就将图片保存到本地。同时,我们添加了两个新的方法blobUrlToBlob和downloadFile。blobUrlToBlob方法是将base64编码后的图片链接转化为Blob对象。 downloadFile方法则是兼容不同浏览器,将图片下载到本地。
如果文件的 MIME 类型与 new Blob() 构造函数传递的类型不匹配,则可能导致解码错误。
示例代码中已经修改成file格式。
<script>
import Compressor from 'compressorjs';
export default {
data () {
return {
fileList: []
};
},
methods: {
compressImage (file) {
return new Promise((resolve, reject) => {
new Compressor(file, {
quality: 0.8, // 压缩质量
maxWidth: 800, // 压缩后的最大宽度
maxHeight: 1200, // 压缩后的最大高度
success (result) {
resolve(result);
},
error (err) {
reject(err);
},
});
});
},
downloadFile (file, filename) {
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(file, filename);
} else {
const link = document.createElement('a');
const body = document.querySelector('body');
link.href = window.URL.createObjectURL(file);
link.download = filename;
// fix Firefox
link.style.display = 'none';
body.appendChild(link);
link.click();
body.removeChild(link);
window.URL.revokeObjectURL(link.href);
}
},
beforeUpload (file) {
this.fileList.push(file);
return false;
},
handleSuccess (response, file, fileList) {
console.log("上传成功");
},
handleError (err, file, fileList) {
console.log("上传失败");
},
async handleChange (file, fileList) {
const compressedFile = await this.compressImage(file.raw);
const fileObj = new File([compressedFile], file.name, { type: compressedFile.type });
this.downloadFile(fileObj, file.name);
},
blobToFile (blob, fileName) {
return new File([blob], fileName, { type: blob.type });
},
blobUrlToBlob (dataURI) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', dataURI, true);
xhr.responseType = 'blob';
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(new Error('下载文件失败'));
}
};
xhr.send();
});
}
}
};
</script>
至此整个下载流程完成