文件轉base64處理或轉換blob對象連接

1、文件轉base64,代碼:ios

axios({
method: 'get',
url: apiPath.common.downloaddUrl,
responseType: 'blob'
}).then(res => {
  console.log(res)
if (res && res.data && res.data.size) {
const dataInfo = res.data
let reader = new FileReader()
reader.readAsDataURL(dataInfo)
reader.onload = function (e) {
const result = e.target.result
    console.log(result) // 打印base64連接
}
} else {
   // 文件損壞或是提示處理
 }
})

Tips、關鍵點:
一、在一個請求中添加 responseType 爲 blob
二、利用 new FileReader() 處理轉化得到


2、文件轉blob對象連接,代碼:axios

axios({
method: 'get',
url: xxx,
responseType: 'blob'
}).then(res => {
  console.log(res)
if (res && res.data && res.data.size) {
const dataInfo = res.data
  const blob = new Blob([dataInfo], {type: dataInfo.type})
  const u = window.URL.createObjectURL(blob)
  console.log(u) // 轉化後的連接
} else {
   // 文件損壞或是提示處理
 }
})

Tips、關鍵點:
一、在一個請求中添加 responseType 爲 blob
二、利用 new Blob() 處理轉化得到
 

3、文件轉blob對象連接後下載,代碼:api

axios({
method: 'get',
url: xxx,
responseType: 'blob'
}).then(res => {
  console.log(res)
if (res && res.data && res.data.size) {
const dataInfo = res.data
   const blob = new Blob([dataInfo], {type: dataInfo.type})
   const u = window.URL.createObjectURL(blob)
   console.log(u) // 轉化後的連接
   let a = document.createElement('a') // 動態建立a連接
  document.body.appendChild(a)
a.href = u
let setDownloadName = 'download' // 默認下載的文件名
downloadName && (setDownloadName = downloadName) // downloadName 爲方法傳進行的值,動態命名。
a.download = setDownloadName
a.click()
window.URL.revokeObjectURL(u) // 移除動態建立的a連接
} else {
   // 文件損壞或是提示處理
 }
})

Tips、關鍵點:
一、在一個請求中添加 responseType 爲 blob
二、利用 new Blob() 處理轉化得到
三、動態建立a連接,並模擬點擊
四、若是須要直接跳轉展現,可把a.download 的相關處理去掉便可

4、base64文件轉blob對象連接,代碼:數組

const b64File = 'data.....'
const contentType = url.substring(5, url.indexOf(';base64')) // 截取文件類型
const b64Data = b64File.substring(b64File.indexOf(',') + 1) // 得到文件頭外的數據
const byteCharacters = atob(b64Data)
const byteNumbers = new Array(byteCharacters.length)
for (let i = 0; i < byteCharacters.length; i++) {
  byteNumbers[i] = byteCharacters.charCodeAt(i)
}
const byteArray = new Uint8Array(byteNumbers)
const blob = new Blob([byteArray], {type: contentType})
const u = window.URL.createObjectURL(blob) // 得到的連接
Tips、關鍵點:一、在base64文件中得到文件類型及真正的文件數據二、利用字節數組處理轉化得到
相關文章
相關標籤/搜索