2016-08-03 35 views
1

我創建了一小段腳本,調用API來獲取PDF並將responseType作爲arraybuffer發送。當下載爲PDF格式時,Chrome會阻止Blob對象

使用此我創建一個新的Blob和類型設置爲「應用程序/ PDF」

要強制此下載我創建了一個錨元素,它傳遞blob和點擊。

這適用於本地和我的測試服務器上的其他瀏覽器,但在Chrome上我很失敗 - 沒有文件在下載欄中。

PDF是絕對可用的,因爲我可以將URL粘貼到API中並將它看到,並將原始API調用的響應傳遞給Blob。

示例代碼

var fileName = 'dummyFilename-' + offerId + '.pdf'; 
var blob = new window.Blob([resData], { type: 'application/pdf' }); 

var anchorElement = document.createElement('a'); 
var url = window.URL.createObjectURL(blob); 

document.body.appendChild(anchorElement); 
anchorElement.id = 'anchorElement'; 
anchorElement.hidden = 'true'; 
anchorElement.href = url; 

if (typeof anchorElement.download !== 'undefined') { 
    anchorElement.download = fileName; 
} else { 
    anchorElement.target = '_blank'; 
} 

anchorElement.click(); 

回答

0

強制這總是有點哈克...:

如果您點擊執行該功能的HTML元素是一個鏈接,你可能想嘗試添加download屬性:

<a href="path/to/your/file.pdf" download>Download PDF</a> 

,如果你願意,你可以將其重命名:

<a href="path/to/your/file.pdf" download="downloaded-pdf-name.pdf">Download PDF</a> 

如果您正在使用的解決方案,以在其他瀏覽器,其中download屬性將只工作,不工作,你的單擊事件處理程序應該是這個樣子:

document.getElementById('#download-pdf').onclick = function (event) { 
    if (!"download" in document.createElement("a")) { 
     // Download is NOT supported, the browser is probably not Chrome 
     // You don't want the native behaviour, which will probably open 
     // the PDF in another tab, so: 
     event.preventDefault(); 

     // TODO: Adapt your code to execute from here... 
    } 
} 

然而,download檢查可能不適用於Firefox。檢查答案這裏的評論:How to detect support for the HTML5 "download" attribute?

如果你有這樣的選擇,我會建議你設置Content-Disposition = 'attachment; filename=downloaded-pdf-name.pdf'在HTTP響應頭。檢查here以查看在不同後端執行此操作的具體方法。

+0

其實我發現我真的只需要Blob就可以在IE下載PDF。最後,我只是將點擊指向一個正常的URL,其下載屬性設置爲強制執行此操作,併爲不支持此操作的瀏覽器打開新的選項卡。我仍然不確定爲什麼Chrome不能正確處理Blob。 –

0

你試過這個嗎? (沒有創建元素)...我希望它有幫助

var fileName = 'dummyFilename-' + offerId + '.pdf'; 
var blob = new window.Blob([resData], { type: 'application/pdf' }); 
// Parse blob object to base64 to prevent chrome blocking: 
var reader = new FileReader(); 
reader.readAsDataURL(blob); 
reader.onloadend = function() { 
    base64data = reader.result; 
    // For IE: 
    if (window.navigator && window.navigator.msSaveOrOpenBlob) { 
     window.navigator.msSaveOrOpenBlob(base64data); 
    } // For webkit 
    else { 
     var objectUrl = URL.createObjectURL(base64data); 
     window.open(objectUrl); 
    } 
}