uniapp小程序上传base64格式的图片
首先可以把图片转base64的方法放在vue原型上,当让也可以写在组件中,在main.js中写入方法
Vue.prototype.pathToBase64 = (path, quality) => {
return new Promise((resolve, reject) => {
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);
resolve({ code: 0, data: base64 });
};
quality = quality * 100 || 30;
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) });
}
);
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) });
},
});
});
};
然后在组件的方法中进行使用
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();
});
},
});
},