JS下載圖片和文件,防止瀏覽器直接打開

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)
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容