2016-07-11 35 views
1

我試圖使用http鏈接下載文件。 這是代碼:下載文本文件或圖像在Firefox上拋出JavaScript

downloadFile: function (fileName, url) { 
    var link = document.createElement('a'); 
    link.setAttribute('download', fileName); 
    link.setAttribute('type', 'application/octet-stream'); 
    link.target = '_blank'; 
    link.href = url; 

    document.body.appendChild(link); 

    link.click(); 

    document.body.removeChild(link); 
} 

這適用於Chrome和邊緣,但不是在Firefox瀏覽器。 當我試圖下載一個文本文件或圖像時,瀏覽器會打開一個新選項卡來顯示文件內容。我需要瀏覽器打開默認的下載窗口。

可能嗎?

這是URL的一個例子,我使用:http://localhost:17671/docstmp/528d149e37467a53faeeeb0556901d87/ToDo.txt

我創造了這個的jsfiddle證明:jsfiddle.net/hp7yod85

+0

豈不正常的下載鏈接工作的結果呢? – Jite

+0

包含'link.setAttribute('type','application/octet-stream')的目的是什麼? link.target ='_blank';'? – guest271314

+0

沒有目標,文件內容與我的應用程序在同一頁面中打開。 並且該類型是嘗試下載的測試 –

回答

0

所請求的資源沒有Access-Control-Allow-Origin頭集,並擁有X-Frame-Options報頭組到SAMEORIGIN以防止加載到元素中。

您可以使用YQL檢索內容,然後在返回的結果創建的文本內容,data URL,然後用href集創建<a>元素data URL。返回預期打開對話框,提示打開文件的文本編輯器中或保存文件在火狐47

<!DOCTYPE html> 
<html> 
<body> 
    <button onclick="downloadFile()">Test</button> 
    <script> 
    function downloadFile() { 
    var request = new XMLHttpRequest(); 
    var url = 'https://query.yahooapis.com/v1/public/yql?q=' 
       + 'select * from html where ' 
       + 'url="http://www.ietf.org/rfc/bcp/bcp47.txt"&format=json&callback=' 
    request.open("GET", url); 
    request.onload = function() { 
     var data = JSON.parse(this.responseText).query.results.body.content; 
     var a = document.createElement("a"); 
     a.href = "data:text/plain," + data; 
     a.download = "bcp47.txt"; 
     document.body.appendChild(a); 
     a.click(); 
     document.body.removeChild(a); 
    } 
    request.send() 
    } 
    </script> 
</body> 
</html> 

plnkr http://plnkr.co/edit/8JBBhVwIy0Icr2MaQZif?p=preview

+0

我認爲這將無法解決,因爲我還可以下載700 MB的大文件,比如rar。像使用此解決方案一樣鎖定用戶將無法從默認下載窗口中看到進度 –

+0

您可以在'XMLHttpRequest'對象中包含'progress'事件以通知用戶文件下載進度。原始問題沒有提及下載700MB文件或「進度」事件? – guest271314

+0

是的,但我將不得不實施取消活動......並且所有事情都由瀏覽器完成 –