uniapp小程式上傳base64格式的圖檔
首先可以把圖檔轉base64的方法放在vue原型上,當讓也可以寫在元件中,在main.js中寫入方法
Vue.prototype.pathToBase64 = (path, quality) => {
return new Promise((resolve, reject) => {
//#ifdef H5
quality = quality || 0.3; // -------------------測試無問題
let img = new Image();
img.src = path;
img.onload = function () {
let that = this,
w = that.width,
h = that.height;
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);
let base64 = canvas.toDataURL("image/jpeg", quality); // quality值越小,所繪制出的圖像越模糊
resolve({ code: 0, data: base64 });
};
//#endif app内部
//#ifdef APP-PLUS
quality = quality * 100 || 30; // --------------------ios說是壓縮有問題,暫時未測 android測試無問題
plus.zip.compressImage(
{
src: path,
dst: "_doc/guoguo.jpg",
overwrite: true,
quality: quality,
format: "jpg",
},
function (res) {
let imgPathUrl = res.target;
let reader = new plus.io.FileReader();
reader.onloadend = (fileData) => {
let base64 = fileData.target.result;
resolve({ code: 0, data: base64 });
};
reader.readAsDataURL(imgPathUrl);
},
function (err) {
resolve({ code: 1, data: "出現錯誤:" + JSON.stringify(err) });
}
);
//#endif 小程式
//#ifdef MP
quality = quality * 100 || 20;
wx.compressImage({
src: path,
quality: quality,
success: (res) => {
wx.getFileSystemManager().readFile({
filePath: res.tempFilePath,
encoding: "base64",
success: function (ret) {
resolve({ code: 0, data: "data:image/jpeg;base64," + ret.data });
},
fail: function (error) {
resolve({
code: 1,
data: "轉base64出現錯誤:" + JSON.stringify(error),
});
},
});
},
fail: (err) => {
resolve({ code: 1, data: "出現錯誤:" + JSON.stringify(err) });
},
});
//#endif
});
};
然後在元件的方法中進行使用
chooseCom3() {
const http = new Request();
// 上傳圖檔
let that = this;
uni.chooseImage({
count: 1,
sizeType: ["compressed"],
sourceType: ["album"], //從相冊選擇
success: function (res) {
let quality = 0.2;
uni.showLoading({ title: "上傳中...", mask: true });
that
.pathToBase64(res.tempFilePaths[0], quality)
.then((resp) => {
if (resp.code == 0) {
//下面是調用接口,這邊這個接口時什麼都不用驗證的
http
.post(`${baseUrl}/applet/app-upload`, {
thumb: resp.data,
})
.then((ret) => {
uni.hideLoading();
if (ret.data.code == 200) {
console.log(ret.data.data.thumb)
}
})
.catch((err) => {
uni.hideLoading();
});
} else {
uni.hideLoading();
}
})
.catch((e) => {
uni.hideLoading();
});
},
});
},