2017-11-25 141 views
0

我有一個有效的網址,我正嘗試使用進行下載。AJAX下載不能正常工作

下面的代碼有什麼問題?

url = "https://firebasestorage.googleapis.com/v0/b/analyst-3206a.appspot.com/o/research_reports%2FNt7cXdWHFlQuwRcy8wo4B49VNeD3%2Fa?alt=media&token=5521f889-2737-4433-a279-f04999cdff22" 

var xhr = new XMLHttpRequest(); 
xhr.responseType = 'blob'; 
xhr.onload = function(event) { 
    var blob = xhr.response; 
}; 
xhr.open('GET', url); 
xhr.send(); 
+0

這個代碼是沒有錯。你是什​​麼意思'不工作'? –

+0

我的意思是沒有下載,它只是默默地運行到完成 – ishandutta2007

+0

你的文件是一個'PNG'格式。看到它的標題:https://imgur.com/a/ZapGY。 –

回答

2

你必須把createObjectURL

url = "https://firebasestorage.googleapis.com/v0/b/analyst-3206a.appspot.com/o/research_reports%2FNt7cXdWHFlQuwRcy8wo4B49VNeD3%2Fa?alt=media&token=5521f889-2737-4433-a279-f04999cdff22" 
 
var a = document.getElementById("a"); 
 
    var xhr = new XMLHttpRequest(); 
 
    xhr.responseType = 'blob'; 
 
    xhr.onload = function (event) { 
 
    var blob = xhr.response; 
 

 
    var a = document.createElement("a"), 
 
     url = window.URL.createObjectURL(blob); 
 
    document.body.appendChild(a); 
 
     a.href = url; 
 
     a.download = "fileName." + blob.type; 
 
     a.click(); 
 
     window.URL.revokeObjectURL(url); 
 

 
    }; 
 
    xhr.open('GET', url); 
 
    xhr.send();

+0

這是下載一個腐敗的pdf。我給的網址是一張圖片。 – ishandutta2007

+2

您可以更改爲:'a.download =「fileName.png」;'。設置擴展名。默認情況下'blob.type'正在返回'pdf' ... –