// 讀取文件結果
afterRead(files) {
let that = this;
let file = files.file;
if (file === undefined) {
return;
}
if (file.size / 1024 > 1025) {
// 文件大於1M(根據需求更改),進行壓縮上傳
this.photoCompress(
file,
{
// 調用壓縮圖片方法
quality: 0.2,
},
function (base64Codes) {
// console.log("壓縮后:" + base.length / 1024 + " " + base);
let bl = that.base64UrlToBlob(base64Codes);
// file.append('file', bl, 'file_' + Date.parse(new Date()) + '.jpg') // 文件對象
that.uploadLice(bl); // 請求圖片上傳接口
}
);
} else {
// 小於等於1M 原圖上傳
this.uploadLice(file);
}
}
/**
* base64 轉 Blob 格式 和file格式
*/
base64UrlToBlob(urlData) {
let arr = urlData.split(","),
mime = arr[0].match(/:(.*?);/)[1], // 去掉url的頭,並轉化為byte
bstr = atob(arr[1]), // 處理異常,將ascii碼小於0的轉換為大於0
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
// 轉blob
// return new Blob([u8arr], {type: mime})
let filename = Date.parse(new Date()) + ".jpg";
// 轉file
return new File([u8arr], filename, { type: mime });
}
/*
壓縮圖片
file:文件(類型是圖片格式),
obj:文件壓縮后對象width, height, quality(0-1)
callback:容器或者回調函數
*/
photoCompress(file, obj, callback) {
let that = this;
let ready = new FileReader();
/* 開始讀取指定File對象中的內容. 讀取操作完成時,返回一個URL格式的字符串. */
ready.readAsDataURL(file);
ready.onload = function () {
let re = this.result;
that.canvasDataURL(re, obj, callback); // 開始壓縮
};
}
/* 利用canvas數據化圖片進行壓縮 */
/* 圖片轉base64 */
canvasDataURL(path, obj, callback) {
let img = new Image();
img.src = path;
img.onload = function () {
let that = this; // 指到img
// 默認按比例壓縮
let w = that.width,
h = that.height,
scale = w / h;
w = obj.width || w;
h = obj.height || w / scale;
let quality = 0.2; // 默認圖片質量為0.7
// 生成canvas
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
// 創建屬性節點
let anw = document.createAttribute("width");
anw.nodeValue = w;
let anh = document.createAttribute("height");
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(that, 0, 0, w, h);
// 圖像質量
if (obj.quality && obj.quality >= 1 && obj.quality < 0) {
quality = obj.quality;
}
// quality值越小,所繪制出的圖像越模糊
let base64 = canvas.toDataURL("image/jpeg", quality);
// 回調函數返回base64的值
callback(base64);
};
}
// 返回file文件,調用接口執行上傳
async uploadLice(files) {
const formData = new FormData();
formData.append("file", files);
let result = await uploadApi(formData);
if (result.code == 200) {
this.sendUrl.push(result.data);
}
}