1、可以直接通過訪問文件的url進(jìn)行下載
<a href="url" download="fileName">download</a>
或者
window.open(url, "_blank");
2、對(duì)于圖片、pdf、txt等瀏覽器支持直接打開預(yù)覽的文件,則不會(huì)進(jìn)行下載
解決辦法:模擬發(fā)送http請(qǐng)求,將文件鏈接轉(zhuǎn)換成文件流,然后使用a標(biāo)簽download屬性進(jìn)行下載。
<button type="button" onclick="download()">點(diǎn)擊下載</button>
function download() {
let url = '文件地址'
let name = '文件名稱'
// 發(fā)送http請(qǐng)求,將文件鏈接轉(zhuǎn)換成文件流
fileAjax(url, function(xhr) {
downloadFile(xhr.response, name)
}, {
responseType: 'blob'
})
}
function fileAjax(url, callback, options) {
let xhr = new XMLHttpRequest()
xhr.open('get', url, true)
if (options.responseType) {
xhr.responseType = options.responseType
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(xhr)
}
}
xhr.send()
}
function downloadFile(content, filename) {
window.URL = window.URL || window.webkitURL
let a = document.createElement('a')
let blob = new Blob([content])
// 通過二進(jìn)制文件創(chuàng)建url
let url = window.URL.createObjectURL(blob)
a.href = url
a.download = filename
a.click()
// 銷毀創(chuàng)建的url
window.URL.revokeObjectURL(url)
}