2012-11-28 42 views
1

我試圖讓我的下載功能彈出與文件下載,它是輸出文件的二進制文件到div當我點擊鏈接,我如何使它,以便當我點擊鏈接,它會問我下載它?我知道我可以使用querystring並在PHP中使用標題,但我可以用ajax/javascript以類似的方式做到這一點嗎?謝謝,這是我的嘗試:如何從javascript下載文件

<html> 
<head> 
<script> 
function Download(plan_name) 
{ 
    if (window.XMLHttpRequest) 
    { 
     xmlhttp=new XMLHttpRequest(); 
    } 
    else 
    { 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 

    xmlhttp.onreadystatechange=function() 
    { 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) 
     { 
      var resp = xmlhttp.responseText; 
      document.getElementById("txtHint").innerHTML=resp; 


      //HOW TO SHOW test.zip in a save-as dialog? 
     } 
    } 

    xmlhttp.open("GET","fetcher.php?file=/raid0/data/naswebsite/Projects/Projects/07-003_Dawson_Mine/Flight\ Plans/Dawson_Sth_1211_AMG_700.zip"); 
    xmlhttp.send(); 
} 

</script> 
</head> 
<body> 

<a href="#" onClick="Download();">Test Download</a> 
<div id="txtHint"></div> 

</body> 
</html> 

回答

2

從AJAX請求下載文件是不可能的。
相反,您可以將URL加載到隱藏的中。

+1

或者做大多數人做的事情,用'window.open'打開一個新窗口並設置它的目標URL,並且使用頭部Content-Disposition:attachment; filename = whatever和/或'Content-Type:application/force-download' – Ian