最近接了一個需求,要求用戶點擊下載按鈕后直接下載pdf文件,而不是打開一個新窗口,讓用戶再去手動保存。
接到需求后我立刻著手在網(wǎng)上查找文檔,發(fā)現(xiàn)很多聲稱可以實現(xiàn)直接下載的方法都不行,只有下面這個方法成功實現(xiàn)了我的需求,現(xiàn)在翻譯過來,供更多的人使用。
原文:How to trigger the direct download of a PDF with JavaScript
現(xiàn)在的web應(yīng)用基本都運行在現(xiàn)代瀏覽器上,科技的進(jìn)步使得我們有很多新的API接口可以調(diào)用,其中一個優(yōu)勢是我們可以直接使用blob和FileReader下載文件,而不用重定向到一個新的標(biāo)簽頁。
在這篇文章中,我將將演示在一個web頁面中,直接通過url下載一個pdf文件。
注意
在案例中我們將下載use a PDF hosted in the Mozilla Github IO website,因為它是免費的而且設(shè)置好了CORS 頭,我們可以在任何地方使用而不用擔(dān)心跨域問題。
依賴
需要使用FileSaver庫來實現(xiàn)下載的目標(biāo)。這個庫支持UMD,所以你可以直接在script標(biāo)簽中引入,也可以引入模塊中使用。
如果你使用npm,你可以這樣安裝它:
npm install file-saver --save
然后你就可以像下面這樣使用它了:
var FileSave = require('file-save');
var blob = new Blob(["hello world!"], {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob, "hello World.txt");
或者
import FileSave from 'file-save';
var blob = new Blob(["hello world!"], {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob, "hello World.txt");
另外,你還可以直接下載FileSaver然后在標(biāo)簽中使用它。
如下首先引入js文件
<script src="FileSaver.min.js"></script>
然后使用
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");
點此點此查看官方文檔
使用url直接下載pdf
多虧了FileSaver.js,你可以很容的用JavaScript在瀏覽器中保存文件數(shù)據(jù)。FileSaver.js實現(xiàn)了瀏覽器不支持直接下載的功能,它是在客戶端下載文件,保存web應(yīng)用數(shù)據(jù),或者發(fā)送到服務(wù)器比較敏感的數(shù)據(jù)。
在這樣的場景下,你想下載服務(wù)器上的pdf文件,但由于某些原因不想讓用戶產(chǎn)生點擊等行為,你可以使用FileSaver.js輕松實現(xiàn)。在下面的例子中,我們通過一個簡單的url下載pdf,根據(jù)你的web應(yīng)用的使用場景,pdf文件僅僅在服務(wù)器滿足某些條件的時候才可以下載,最后通過JavaScript下載和處理。
var oReq = new XMLHttpRequest();
// The Endpoint of your server
var URLToPDF = "https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf";
// Configure XMLHttpRequest
oReq.open("GET", URLToPDF, true);
// Important to use the blob response type
oReq.responseType = "blob";
// When the file request finishes
// Is up to you, the configuration for error events etc.
oReq.onload = function() {
// Once the file is downloaded, open a new window with the PDF
// Remember to allow the POP-UPS in your browser
var file = new Blob([oReq.response], {
type: 'application/pdf'
});
// Generate file download directly in the browser !
saveAs(file, "mypdffilename.pdf");
};
oReq.send();
當(dāng)文件下載結(jié)束的時候,保存程序會自動開始保存。
提醒一下哦,如果瀏覽器不支持Blob,可以使用這個補(bǔ)丁哦.
喜歡的同學(xué)可以去我的博客逛逛哦