2011-08-03 23 views
-3

如何用JavaScript下載文件only如何用JavaScript下載文件

請不要給我回答這樣

"Change theMIMEin the sever"

window.open(URL,"_blank")

因爲我知道還有另一種解決方案。謝謝。

編輯:
文件我想下載一個.JSON文件。

+5

如果你知道有其他的解決方案......你爲什麼要問? –

+0

那麼,什麼樣的文件? –

+1

如果您要求在阻止所有其他下載的同時允許從JavaScript啓動下載,則不能。服務器應該如何告知非JavaScript JavaScript請求?什麼狀態可以在JavaScript中進行變異,而不會被確定的用戶欺騙?沒有,據我所知。 – aroth

回答

9

您可以動態創建iframe並將其位置設置爲您要下載的URL。

var f = document.createElement("iframe"); 
f.setAttribute("id", "theFrame"); 
document.body.appendChild(f); 
document.getElementById("theFrame").location = 'http://www.example.com/yourfile.doc'; 

不知道上述工作是否正常。如果沒有,嘗試在最後一行src,而不是location設置它:

document.getElementById("theFrame").src = 'http://www.example.com/yourfile.doc'; 
+0

甚至更​​簡單:'window.location.href ='http://www.example.com/yourfile.doc';' – aroth