場景:上傳給後臺前,如果圖片過大,需要壓縮一下再上傳給後臺
在vue項目中可以使用localResizeIMG插件進行壓縮
- 在項目內與後臺商定的圖片接口:直接傳一個formData對象(裏面需包含file文件與接口方法參數)
- lrz接口回調放回有壓縮後的file(blob對象)、formData對象(包含file對象)
開始!!
安裝插件:
npm i lrz -save
yarn add lrz -S
//yarn 安裝
引入
在main.js里加入:import lrz from ‘lrz’
//不用vue.use就可以直接引用
代碼
var localFile = document.getElementById("uploadFileAdd").files[0];
// 判斷大小
const isLt10M = localFile.size / 1024 / 1024 < 10;
if (!isLt10M) {
this.showToast(true, "上傳圖片大小不能超過 10MB!");
return;
}
var thes = this;
// 壓縮圖片
lrz(localFile, {
quality:0.6
}).then(function(rst) {
rst.formData.append("type", thes.imgType);
rst.formData.append("service", "UploadFileService");
rst.formData.append("sysAppName", "business");
rst.formData.append("method", "upload");
thes.$store
.dispatch("order/getOrderList", rst.formData)
.then(res => {
let img = { url: res.filePath };
thes.fileList.push(img);
thes.showToast(true, "圖片上傳成功");
})
.catch(e => {
console.log("res11", res);
});
}).catch(function(error) {
console.log("erroree",error);
}).always(function() {
console.log("alway");
})
lrz函數解析
lrz( file, [ options ] )
.then(function(rst) {
//成功時執行回調
}).catch(function(error) {
//失敗時執行回調
}).always(function() {
//不管成功或失敗,都會執行
})
官方api
lrz(file, [options]);
[options] 這個參數允許忽略
width {Number} 圖片最大不超過的寬度,默認爲原圖寬度,高度不設時會適應寬度。
height {Number} 同上
quality {Number} 圖片壓縮質量,取值 0 - 1,默認爲0.7
fieldName{String} 後端接收的字段名,默認:file
官方插件GitHub地址:lrz