2011-10-10 35 views
32

我正在使用純Javascript編寫文本編輯器。我喜歡這樣,當用戶點擊「保存」按鈕時,編輯器會下載文件。我已經有這部分工作:保存文件帶有文件名的Javascript

uriContent = "data:application/octet-stream," + encodeURIComponent(codeMirror.getValue()); 
newWindow=window.open(uriContent, 'filename.txt'); 

的文件下載,但問題是,該文件名爲「下載」。

問題:如何將文件的名稱更改爲我想要的任何內容,例如filename.txt

+0

@zzzzBov我想:http://jsfiddle.net/Qjvb3/

這裏download屬性的兼容性表這個答案比你鏈接的更好,因爲它實際上爲所述問題提供瞭解決方案。 – Deviljho

+0

@AdriánSalgado,這不會使這個問題成爲重複,但是這個近距離投票發生在2年前。正如你所看到的,沒有足夠的支持來真正關閉這個問題。如果你認爲其他問題應該有更好的答案,那麼我建議增加一個。 – zzzzBov

+0

似乎沒有任何好的答案呢!這只是在javascript窗口對象中的一個小黑洞,我猜!我也有同樣的擔憂:我的代碼會隨時打開包含報告的文件,但文件名不是我的代碼定義的。我不應該要求用戶點擊href並下載文件。 –

回答

23

用錨鏈接替換您的「保存」按鈕並動態設置新的download屬性。工程在Chrome和Firefox:

var d = "ha"; 
$(this).attr("href", "data:image/png;base64,abcdefghijklmnop").attr("download", "file-" + d + ".png"); 

這裏的設置爲當前日期名稱的工作例如:http://caniuse.com/download

+1

下載屬性瀏覽器支持http://caniuse.com/#feat=download – jcubic

+0

如上所述,Safari和IE中沒有下載屬性支持。 – LT86

5

使用filename屬性是這樣的:

uriContent = "data:application/octet-stream;filename=filename.txt," + 
       encodeURIComponent(codeMirror.getValue()); 
newWindow=window.open(uriContent, 'filename.txt'); 

編輯:

顯然,有做這種沒有可靠的方法。請參閱:Is there any way to specify a suggested filename when using data: URI?

+0

嗯,我試過了,它仍在下載一個名爲'download'的文件。 這是我現在的代碼: 'uriContent =「data:application/octet-stream; filename = filename.txt,」+ encodeURIComponent(codeMirror.getValue()); newWindow = window.open(uriContent,'filename.txt');' – skimberk1

+2

似乎不適用於我在Firefox中完成的瀏覽器測試;這是不同瀏覽器的功能嗎? [Wikipedia提到數據URL不能帶有文件名](http://en.wikipedia.org/wiki/Data_URI_scheme#Disadvantages)。 – zzzzBov

+0

嗯好的,謝謝你的答案! – skimberk1

13
function saveAs(uri, filename) { 
    var link = document.createElement('a'); 
    if (typeof link.download === 'string') { 
     document.body.appendChild(link); // Firefox requires the link to be in the body 
     link.download = filename; 
     link.href = uri; 
     link.click(); 
     document.body.removeChild(link); // remove the link when done 
    } else { 
     location.replace(uri); 
    } 
} 
+0

你救了我的生命兄弟。謝謝 –

相關問題