一、文件轉base64,代碼:
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、關鍵點:
1、在一個請求中添加 responseType 為 blob
2、利用 new FileReader() 處理轉化獲得
二、文件轉blob對象鏈接,代碼:
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、關鍵點:
1、在一個請求中添加 responseType 為 blob
2、利用 new Blob() 處理轉化獲得
三、文件轉blob對象鏈接后下載,代碼:
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、關鍵點:
1、在一個請求中添加 responseType 為 blob
2、利用 new Blob() 處理轉化獲得
3、動態創建a鏈接,並模擬點擊
4、如果需要直接跳轉展示,可把a.download 的相關處理去掉即可
四、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、關鍵點:
1、在base64文件中獲得文件類型及真正的文件數據
2、利用字節數組處理轉化獲得