大家好,在这里记录一篇困扰了我一天的问题:Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'. at eval (test.vue:121) ,因为我是用uni.app
上传的照片,然后上传之后显示照片的路径为blob:http://..............但是我要的是base64格式的照片传给后端,所以我现在要将blog格式的照片转换成base64
一、使用常见的readAsDataURL()方法等
不出意外还是同样的报错:
Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'. at eval (test.vue:121)
总之,找了很多例如将blob转换成url,再将url转换成base64,或者将blob直接转换成base64等等,但都是错的,毫无变化;
二、使用uni.app来操作
onChooseImage() {
uni.chooseImage({
count: 1,
fail: () => {
this.$u.toast('选择照片失败')
},
success: (res) => {
let blob = res.tempFilePaths[0]
//获取blob
this.blobToBase64(blob, 300).then(res => {
console.log('base64=='+res)
})
}
})
},
blobToBase64(blob, wid) {
return new Promise((resolve, reject) => {
let image = new Image();
image.onload = function() {
let canvas = document.createElement('canvas');
var w = this.naturalWidth,
h = this.naturalHeight,
scale = w / h;
w = wid || w;
h = w / scale;
canvas.width = w
canvas.height = h;
// 将图片插入画布并开始绘制
canvas.getContext('2d').drawImage(image, 0, 0, w, h);
// result
let result = canvas.toDataURL('image/png')
resolve(result);
};
image.setAttribute("crossOrigin", 'Anonymous');
image.src = blob;
// 图片加载失败的错误处理
image.onerror = () => {
reject(new Error('urlToBase64 error'));
};
})
},