vue 公众端使用微信sdk上传图片大坑

废话不多说,趟过的坑想帮助更多人而已,直接上代码



本人亲测有效

整体思路就是 首先引入微信的sdk,附上文档

微信sdk文档

引入成功以后可以在微信开发工具中看是否引入成功

进入主题

第一步 先通过 wx.getLocalImgData() 拿到图片ID

update(e) {

let _this = this;

let param = new FormData();

wx.chooseImage({

count: 1, // 默认9

sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有

sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有

success: function(res) {

_this.localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片\

wx.getLocalImgData({

localId: res.localIds[0], // 图片的localID

success: function(ress) {

let bs64 = ress.localData; //  localData是图片的base64数据,可以用img标签显示

// 去掉所以换行符

//因为微信返回的base64是没有前缀的,所以需要手动添加并去掉换行等

_this.localData = 'data:image/jpeg;base64,' + bs64.replace(/\r|\n/g, '');  //此处是一个坑

//因为选择的图片一般都很大,所以需要二次转码(Blob)  也就是二进制

console.log(_this.dataURItoBlob(_this.localData));//坑2  此处必须做!必须做!必须做!

param.append('file', _this.dataURItoBlob(_this.localData));

_this.$http.put('/api/user_info', param).then(response => {

console.log(response.data);

});

}

});

}

});

},

dataURItoBlob(dataURI) {

// convert base64/URLEncoded data component to raw binary data held in a string

let byteString;

if (dataURI.split(',')[0].indexOf('base64') >= 0) {

byteString = atob(dataURI.split(',')[1]);

} else byteString = unescape(dataURI.split(',')[1]);

// separate out the mime component

const mimeString = dataURI

.split(',')[0]

.split(':')[1]

.split(';')[0];

// write the bytes of the string to a typed array

const ia = new Uint8Array(byteString.length);

for (let i = 0; i < byteString.length; i++) {

ia[i] = byteString.charCodeAt(i);

}

return new Blob([ia], { type: mimeString });

},

方式很简单,但是通用大部分,亲测有用!绝对是干货,建议收藏

我叫王小二,一个不起眼的前端小白,若有不足请各位大佬多多指教.....................

你可能感兴趣的:(vue 公众端使用微信sdk上传图片大坑)