2015-06-20 76 views

回答

1

您不需要AJAX來做到這一點,也不會因爲CORS限制而能夠做到這一點。相反,嘗試這樣的事情。

HTML:

<input type="text" placeholder="URL" id="url"/> 
<input type="text" placeholder="Filename" id="name"/> 
<a id="download">Download Link</a> 

的JavaScript:

var url = document.getElementById('url'), 
    name = document.getElementById('name'), 
    a = document.getElementById('download'); 

a.addEventListener('click', function() { 
    this.setAttribute('src', url.value); 
    this.setAttribute('download', name.value); 
}); 
2

第一種方法

function SaveToDisk(fileURL, fileName) { 
       //alert("yes i m working"); 
       // for non-IE 
       if (!window.ActiveXObject) { 
        var save = document.createElement('a'); 
        save.href = fileURL; 
        save.target = '_blank'; 
        save.download = fileName || 'unknown'; 

        var evt = new MouseEvent('click', { 
         'view': window, 
         'bubbles': true, 
         'cancelable': false 
        }); 
        save.dispatchEvent(evt); 

        (window.URL || window.webkitURL).revokeObjectURL(save.href); 
       } 

       // for IE < 11 
       else if (!! window.ActiveXObject && document.execCommand)  { 
        var _window = window.open(fileURL, '_blank'); 
        _window.document.close(); 
        _window.document.execCommand('SaveAs', true, fileName || fileURL) 
        _window.close(); 
       } 
      } 

第二種方法

function downloadme(x,y){ 

     myTempWindow = window.open(x,'','left=10000,screenX=10000'); 
     myTempWindow.document.execCommand('SaveAs','null',y); 
     myTempWindow.close(); 
    } 
+0

的瀏覽器通常足夠複雜以阻止點擊生成的鼠標事件的錨點標記,請注意此限制。 –

+0

第一種方法的作品,謝謝,但是如何在這段代碼中我可以改變目錄來保存文件? – mvoron

+0

@mvoron - 這是強制下載好友。 – Bugfixer