博客 / 詳情

返回

一張base64圖片格式的圖片,將其轉化成blob然後上傳到服務器

一張base64圖片格式的圖片,將其轉化成blob然後上傳到服務器

需求描述

一張base64圖片格式的圖片,將其轉化成blob然後上傳到服務器,後台跟接收表單文件上傳一樣的方式去處理改圖片

實現

// url 表示base64的字符串, name表示文件名,附加到blob上的那麼、上
uploadFile(url, name) {
            // 以逗號劃分類型和內容
            let arr = url.split(',')
            // 截取類型
            let mime = arr[0].match(/:(.*);/)[1]
            // 將base64格式的字符轉回原本的字符格式
            let bstr = window.atob(arr[1])
            let n = bstr.length,
            u8arr = new Uint8Array(n)
            while (n--) {
                // 將ascll碼值儲存到無符號數組中
                u8arr[n] = bstr.charCodeAt(n)
            }
            // 轉化blob
            let blob = new Blob([u8arr], { type: mime })
            blob.lastModifiedDate = new Date()
            blob.name = name
            // 構造FormData
            let formData = new FormData();
            formData.append('time', moment().format('YYYYMMDD'))
            formData.append('file', blob)
            console.log(blob)
              // 發送請求
            stationData.uploadImg(formData).then(res => {
                console.log('aasad', res)
            })
        },

總結

在這裏插入圖片描述
這裏是通過blob可以接收一個ArrayBuffer的參數的形式去創建一個blob

user avatar peter-wilson 頭像 tigerandflower 頭像 codepencil 頭像 shaochuancs 頭像 sunhengzhe 頭像 uncletong_doge 頭像 jianqiangdepaobuxie 頭像 gaoming13 頭像 frontoldman 頭像 kevin_5d8582b6a85cd 頭像 qianduanlangzi_5881b7a7d77f0 頭像 pangsir8983 頭像
25 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.