js接收客户端base64图片转换Blob

大致场景就是前端通过jsBridge获取客户端返回的base64图片数据,然后将base64的数据转为Blob图片,然后拿着这个Blob图片文件上传到阿里云去!对,就是这个意思,接下来请欣赏项目中滴代码:

// 将以base64的图片url数据转换为Blob
convertBase64UrlToBlob(urlData) {
    var binary = atob(urlData)
    var array = []
    for (var i = 0, len = binary.length; i < len; i++) {
        array.push(binary.charCodeAt(i))
    }
    return new Blob([new Uint8Array(array)], { type: 'image/jpeg' })
},
iosUploadPic() {
    this.$jsBridge.callHandler('web_uploadImage', {}, (base64Codes) => {
        base64Codes = base64Codes.replace(/\s/g, '')
        // var formData = new FormData()
        // formData.append('file', this.convertBase64UrlToBlob(base64Codes))
        // alert(this.convertBase64UrlToBlob(base64Codes).name)
        // 图片显示
        // const reader = new FileReader()
        // reader.onload = (e) => {
        //     this.imgUrl = 'data:image/png;base64,' + base64Codes
        // }
        // reader.readAsDataURL(this.convertBase64UrlToBlob(base64Codes))
        this.uploadFile = this.convertBase64UrlToBlob(base64Codes)
        this.$apis.getAvatarUploadInfo({'fileName': 'default.jpg'}).then(res => {
            if (res.code === '000') {
                let objectName = res.data.key
                let downloadPath = res.data.downloadPath
                let OSS = require('ali-oss')
                let client = new OSS({
                    region: res.data.regionId,
                    accessKeyId: res.data.accessKeyId,
                    accessKeySecret: res.data.accessKeySecret,
                    stsToken: res.data.securityToken,
                    bucket: res.data.bucket
                })
                const put = async() => {
                    try {
                        let result = await client.put(objectName, this.uploadFile)
                        if (result.res.statusCode === 200) {
                            this.$sdkToast({
                                message: '上传成功'
                            })
                            // this.imgUrl = result.url
                            this.imgUrl = downloadPath
                        } else {
                            this.$sdkToast({
                                message: '上传失败'
                            })
                            this.imgUrl = ''
                        }
                    } catch (e) {
                        this.$sdkToast({
                            message: e
                        })
                    }
                }
                put()
            } else {
                this.$sdkToast({
                    message: res.message
                })
            }
        }).catch((error) => {
            this.uploading = false
            this.$sdkToast({
                message: error
            })
        })
    })
}

 

你可能感兴趣的:(JavaScript,/,jQuery)