微信圖片上傳方案

微信圖片上傳方案

如今上線的方案爲:

註冊微信JSSDK -> wx.chooseImage 喚起相機選擇圖片 -> wx.uploadImage 上傳圖片至微信服務器 -> wx.downloadImage 圖片下載到本地 -> wx.getLocalImgData 找到本地圖片生成base64 -> base64轉文件以後 調用咱們的圖片上傳接口(baseSave.json) ->接口返回圖片地址,拼接域名+/picture/+*** 展現圖片前端

//選擇圖片
    addImageMethod = (imageName) => {
        Toast.loading('喚起相機中,請稍等...', 2);
        changeImage = imageName;
        let that = this;
        //喚起相機
        wx.chooseImage({
            count: 1, // 默認9
            sizeType: ['original', 'compressed'], // 能夠指定是原圖仍是壓縮圖,默認兩者都有
            sourceType: ['camera'], // 能夠指定來源是相冊仍是相機,默認兩者都有
            success: function (res) {
                Toast.hide();
                that.uploadFile(res.localIds);
            },
            fail: function (err) {
                Toast.hide();
                Modal.alert('警告', '請確保微信權限都已開啓,否則沒法正常調用相機功能', [
                    { text: '知道了', onPress: () => console.log('cancel') },
                ])
            }
        })
    }
    //上傳圖片
    uploadFile = (localIds) => {
        let that = this;
        wx.uploadImage({
            localId: localIds.toString(),
            success: function (data) {
                that.downloadImage(data.serverId)
            },
            fail: function (data) {
                Toast.info('上傳圖片失敗,請聯繫客服', 2);
            }
        });
    }
    //下載圖片接口
    downloadImage = (serverId) => {
        let that = this;
        wx.downloadImage({
            serverId: serverId, // 須要下載的圖片的服務器端ID,由uploadImage接口得到
            isShowProgressTips: 1, // 默認爲1,顯示進度提示
            success: function (res) {

                var localId = res.localId; // 返回圖片下載後的本地ID
                that.getLocalImgData(localId)
            },
            fail: function (data) {
                Toast.info('上傳圖片失敗,請聯繫客服', 2);
            }
        })
    }
    //獲取本地圖片接口
    getLocalImgData = (serverId) => {
        let that = this;
        wx.getLocalImgData({
            localId: serverId, // 圖片的localID
            success: function (res) {

                var localData = res.localData; // localData是圖片的base64數據,能夠用img標籤顯示
                that.uploadFileBase(res.localData)
            },
            fail: function (data) {
                Toast.info('上傳圖片失敗,請聯繫客服', 2);
            }
        })
    }
    //上傳圖片到本身的服務器
    uploadFileBase = (base64Data) => {
        let blob = '';
        if (base64Data.indexOf("base64") > -1) {

            blob = this.dataURLtoBlob(base64Data);
        } else {

            blob = this.dataURLtoBlob("data:img/jpg;base64," + base64Data);
        }

        let file = this.blobToFile(blob, '123.jpg');

        let formdata = new FormData();
        formdata.append('file', file, '123.jpg');

        const url = '/upload/***';
        let that = this;
        Toast.loading('Loading...', 5);
        fetch(url, {
            method: 'POST',
            mode: 'cors',
            body: formdata,
            dataType: 'json',
        }).then(function (response) {
            return response.json();
        }).then(function (data) {
            Toast.hide()
            if (data.success) {
                Toast.info(data.message || '上傳成功', 2);
                if (changeImage == 'image1') {
                    that.setState({
                        image1: "/picture/" + data.items[0]
                    })
                    imageData.image1 = "/picture/" + data.items[0];
                    sessionStorage.setItem('identityCard', JSON.stringify(imageData));
                } else {
                    that.setState({
                        image2: "/picture/" + data.items[0]
                    })
                    imageData.image2 = "/picture/" + data.items[0];
                    sessionStorage.setItem('identityCard', JSON.stringify(imageData));
                }
            } else {
                Toast.info(data.message || '上傳失敗', 2);
            }
        }).catch(error => console.log("error=" + error));
    }
    //將base64轉換爲blob
    dataURLtoBlob = (dataurl) => {
        var arr = dataurl.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {
            type: mime
        });
    }
    //將blob轉換爲file
    blobToFile = (blob, fileName) => {
        blob.lastModifiedDate = new Date();
        blob.name = fileName;
        return blob;
    }

複製代碼

** 注意: base64在轉blob時 由於wx返回的base64在安卓手機和IOS手機 不一樣:一個會有data:img/jpg;base64, 一個沒有。因此須要進行處理後再轉Bolb **json

前端理想解決方案:

依然依賴微信JSSDK,由於微信已經作好了手機兼容性以及多選圖片的功能與圖片的壓縮,安全性更高而且能夠知足更多的業務需求。

註冊微信JSSDK -> wx.chooseImage 喚起相機選擇圖片 -> wx.uploadImage 上傳圖片至微信服務器 -> 將圖片ID傳給後端,後端經過接口獲取圖片,下載到咱們的服務器,而後返回圖片在咱們服務器的地址->返回下載成功後端

不依賴微信JSSDK,經過H5實現圖片上傳。

須要考慮各個手機,各個版本微信的兼容性。 H5選擇圖片 只支持單選。 須要考慮圖片壓縮問題安全

相關文章
相關標籤/搜索