前端預覽與下載PDF小結


項目中經常會遇到pdf的下載和預覽的功能,那么我們該如何實現呢?

 

前提1:后台返回的是文件地址(非文件流)

下載:

<a href="/1.pdf" target="_blank" download>下載</a>
加上download即可。

預覽:

<a href="/1.pdf" target="_blank">下載</a>

預覽需要去掉download屬性。

前提2:后台返回文件流地址

下載:

方法1:

<a href="http://test.pdf">下載</a>  
<a
            :href="
              SYS_URL +
                '/sa/panorama/downExcel?templateId=' +
                record.templateId +
                '&templateName=' +
                record.templateName +
                ''
            "
            ><a-button> 下載模版 </a-button></a
   >
直接默認就可以下載,其實也就是相當於用a標簽來進行get請求,地址就是直接能夠獲取文件流的地址,地址可以傳參,也可以不傳參,根據實際接口要求來定。
 
方法2:
利用get請求,並且  responseType: "blob", 設置返回的請求是blob類型,來請求獲取具體的文件流,然后經過處理后可以下載文件。
axios({
        url: `/admin/file/getFileByName?fileName=${fileName}`,
        method: "get",
        responseType: "blob",
      }).then((response) => {
        // 處理返回的文件流
        const blob = response.data;
        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = '文件名稱';
        document.body.appendChild(link);
        link.click();
        window.setTimeout(function () {
          URL.revokeObjectURL(blob);
          document.body.removeChild(link);
        }, 0);
 });

 

預覽:

需要插件支持。如果pdf.js  或者  vue-pdf 等插件。

 

小結:不論后台返回的是文件或者文件流,其實對於下載來說都是好處理的。而對於如果是文件流來說,想在谷歌瀏覽器預覽,則還需要額外的插件,才能預覽。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM