下載按鈕直接下載圖片或pdf而不是打開(kāi)圖片或pdf

我也是網(wǎng)上抄的復(fù)制下面兩個(gè)方法,直接調(diào)用fileLinkToStreamDownload 就能下載

function fileLinkToStreamDownload(url, fileName, type){
let reg = /^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-]+).)+([A-Za-z0-9-/])+/; if (!reg.test(url)) { throw new Error("傳入?yún)?shù)不合法,不是標(biāo)準(zhǔn)的文件鏈接"); } else { let xhr = new XMLHttpRequest(); xhr.open('get', url, true); xhr.setRequestHeader('Content-Type', `application/{type}`);
xhr.responseType = "blob";
xhr.onload = function () {
if (this.status == 200) {
//接受二進(jìn)制文件流
var blob = this.response;
downloadExportFile(blob, fileName, type)
}
};
xhr.send();
}
}

/**
*下載導(dǎo)出文件

  • @param blob :返回?cái)?shù)據(jù)的blob對(duì)象或鏈接
  • @param tagFileName :下載后文件名標(biāo)記
  • @param fileType :文件類(lèi) word(docx) excel(xlsx) ppt等
    */
    function downloadExportFile(blob, tagFileName, fileType) {
    let downloadElement = document.createElement('a');
    let href = blob;
    if (typeof blob == 'string') {
    downloadElement.target = '_blank';
    } else {
    href = window.URL.createObjectURL(blob); //創(chuàng)建下載的鏈接
    }
    downloadElement.href = href;
    downloadElement.download = tagFileName + moment(new Date().getTime()).format('YYYYMMDDhhmmss') + '.' + fileType; //下載后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //點(diǎn)擊下載
    document.body.removeChild(downloadElement); //下載完成移除元素
    if (typeof blob != 'string') {
    window.URL.revokeObjectURL(href); //釋放掉blob對(duì)象
    }
    }

抄的原博客地址 https://www.cnblogs.com/jackson-yqj/p/11321275.html

最后編輯于
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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