js接收客戶端base64圖片轉換Blob
阿新 • • 發佈:2019-01-05
大致場景就是前端通過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 }) }) }) }