前端下載文件而不是打開預(yù)覽(支持 doc / excel / ppt / pdf 等)

前端根據(jù)后臺(tái)返回的文件地址(非跨域),實(shí)現(xiàn)點(diǎn)擊下載文件

a 標(biāo)簽下載文件,download屬性可以實(shí)現(xiàn)對下載文件的重命名

<a download="文件名稱" href="文件地址">下載</a>

在Chrome瀏覽器中,使用a標(biāo)簽屬性download下載pdf鏈接文件,如果是相同域時(shí),可以直接下載;跨域會(huì)直接打開頁面預(yù)覽文件;

IE瀏覽器下 download 修改文件名失效

修改:

//文件地址非跨域
<a  href="javascript:void(0)" onClick={()=>this.download(url)}>下載</a>

js

getBlob = (url) => {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest();

      xhr.open('GET', url, true);
      xhr.responseType = 'blob';
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        }
      };

      xhr.send();
    });
}
saveAs = (blob, filename) => {
    if (window.navigator.msSaveOrOpenBlob) {
      navigator.msSaveBlob(blob, filename);
    } else {
      const link = document.createElement('a');
      const body = document.querySelector('body');

      link.href = window.URL.createObjectURL(blob);
      link.download = filename;

      // fix Firefox
      link.style.display = 'none';
      body.appendChild(link);

      link.click();
      body.removeChild(link);

      window.URL.revokeObjectURL(link.href);
    }
}
download = (url) => {
    let filename="xxxxx";
    this.getBlob(url).then(blob => {
      this.saveAs(blob, filename);
    });
}

參考:
https://www.cnblogs.com/jackson-yqj/p/11321275.html
https://blog.csdn.net/borage21/article/details/108253737
https://www.cnblogs.com/ygunoil/p/12565565.html

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

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

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