downloadFileFromBlobByToken
pdf 等所有文件通过blog强制下载函数 downloadFileFromBlobByToken
import { getToken } from '@/libs/util'
export const downloadFile = src => {
console.log(src)
let iframe = document.createElement('iframe')
iframe.src = src
iframe.style.display = 'none'
iframe.style.height = 0
document.body.appendChild(iframe)
setTimeout(() => {
iframe.remove()
}, 3000)
}
/* 通过BLob文件来下载保存文件 */
const downloadFileFromBlob = (blob, fileName) => {
// fileName 一定是要带后缀名的,而且要和blob匹配,否则下载文件打不开
if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE系列兼容,兼容IE10+,Edge12-18
window.navigator.msSaveOrOpenBlob(blob, fileName)
} else {
const downloadElement = document.createElement('a')
const href = window.URL.createObjectURL(blob)
downloadElement.href = href
downloadElement.download = fileName
document.body.appendChild(downloadElement)
downloadElement.click()
document.body.removeChild(downloadElement)
window.URL.revokeObjectURL(href)
}
}
const getFilenameFromUrl = (url) => {
var anchor = url.indexOf('#')
var query = url.indexOf('?')
var end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length)
return url.substring(url.lastIndexOf('/', end) + 1, end)
}
const populateIframe = (url, headers, callback) => {
var xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.responseType = 'blob'
headers.forEach((header) => {
xhr.setRequestHeader(header[0], header[1])
})
xhr.onreadystatechange = () => {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
// const disposition = xhr.getResponseHeader('content-disposition')
// console.info('xhr.getAllResponseHeaders()', xhr.getAllResponseHeaders())
// console.info('disposition', disposition)
// const matched = /.*filename=(.*)/.exec(disposition) // 匹配
// console.info('matched', matched)
// const matchStr = matched?.[1]?.trim()
// console.info('matchStr', matchStr)
// console.info('decodeURI(matchStr)', decodeURI(matchStr))
// console.info('decodeURIComponent(escape(matchStr))',
// decodeURIComponent(escape(matchStr)))
// console.info('1+2+3',
// decodeURI(decodeURIComponent(escape(matchStr))))
// downloadFileFromBlob(xhr.response, decodeURI(matchStr))
const fileName = getFilenameFromUrl(url)
console.info('fileName', fileName)
downloadFileFromBlob(xhr.response, decodeURI(fileName))
// downloadFileFromBlob(xhr.response, decodeURIComponent(escape(matchStr)))
// callback && callback(URL.createObjectURL(xhr.response))
// callback && callback(URL.createObjectURL(xhr))
// callback && callback(URL.createObjectURL(xhr.response))
}
}
}
xhr.send()
}
export const downloadFileFromBlobByToken = (downloadFileUrl) => {
console.info('downloadFileFromBlobByToken downloadFileUrl', downloadFileUrl)
const headers = [
['token', getToken()]
]
populateIframe(downloadFileUrl, headers)
}
标签:info,downloadFileFromBlobByToken,const,url,matchStr,console,blog,xhr,pdf
From: https://www.cnblogs.com/pengchenggang/p/17576870.html