js鏈接直接下載文件

1、需求

  • .html,.text,.pdf...等文件通過a標(biāo)簽直接打開鏈接瀏覽器會默認(rèn)打開;
  • 業(yè)務(wù)需求通過文件鏈接地址直接打開文件,而不是打開

2、嘗試

  • 直接使用a標(biāo)簽,只支持excel,等文件直接下載,且無法設(shè)置下載文件名
function downloadFileByBlob(Url, filename) {
    const eleLink = document.createElement('a')
    eleLink.download = filename
    eleLink.style.display = 'none'
    eleLink.href = Url
    // 觸發(fā)點擊
    document.body.appendChild(eleLink)
    eleLink.click()
    URL.revokeObjectURL(Url) // 釋放URL 對象
    // 然后移除
    document.body.removeChild(eleLink)
}
  • 使用xhr請求,獲取blob數(shù)據(jù)(會存在跨域,需要后端配合處理,較麻煩不推薦)
/**
 * 獲取頁面文件名
 * @param url 文件url
 */
function downloadUrlFile(url) {
    url = url.replace(/\\/g, '/');
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    //xhr.setRequestHeader('Authorization', 'Basic a2VybWl0Omtlcm1pdA==');
    xhr.onload = () => {
        if (xhr.status === 200) {
            // 獲取文件blob數(shù)據(jù)并保存
            var fileName = getFileName(url);
            saveAs(xhr.response, fileName);
        }
    };
 
    xhr.send();
}
 
/**
 * URL方式保存文件到本地
 * @param data 文件的blob數(shù)據(jù)
 * @param name 文件名
 */
function saveAs(data, name) {
    var urlObject = window.URL || window.webkitURL || window;
    var export_blob = new Blob([data]);
    var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a')
    save_link.href = urlObject.createObjectURL(export_blob);
    save_link.download = name;
    save_link.click();
}
 
/**
 * 根據(jù)文件url獲取文件名
 * @param url 文件url
 */
function getFileName(url) {
    var num = url.lastIndexOf('/') + 1
    var fileName = url.substring(num)
        //把參數(shù)和文件名分割開
    fileName = decodeURI(fileName.split("?")[0]);
    return fileName;
}

3、 具體實現(xiàn)

  • 使用fetch,解決跨域,獲取文件blob數(shù)據(jù)再下載,可以直接設(shè)置文件名
export function downloadName(url, filename) {
    fetch(url, {
        mode: 'no-cors', // 必要設(shè)置,解決跨域
    }).then(async res => {
        let blob = await res.blob()
        return blob
    }).then((blob) => {
        const a = document.createElement('a')
        a.style.display = 'none'
        a.href = URL.createObjectURL(blob)
        a.download = filename
        a.target = '_blank'
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
    })
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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