2009-03-04 25 views
23

我被要求製作一個「下載」按鈕,將文本的內容作爲文件下載到同一頁面上,瀏覽器的「另存爲...「對話框出現。複製/粘貼會很好地完成這項工作,但這是一項「要求」。將textarea內容作爲僅使用Javascript的文件下載(無服務器端)

現在,我只是發佈textarea的內容到服務器,這與echoslack在他們回來。有沒有一種方法只用客戶端的Javascript來做到這一點?

回答

2

簡短的回答:這不是可能的。 您必須將其發佈到服務器,並且來自服務器的響應可以是「內容處置:附件」。

9

你可以嘗試window.location = "data:application/octet-stream,"+text但這並不提供一種機制,通過它你可以建議一個名稱,而且IE在數據URI的最大長度上有一個很小的限制,這可能是一個問題。

+2

而IE6甚至不可能。 – 2009-03-04 07:39:24

+0

很酷。 http://en.wikipedia.org/wiki/Data_URI_scheme – Thilo 2009-03-04 07:42:05

1

通過創建一個框架,寫作內容有,然後調用IE document.execCommand('saveas', ...)與nsIFilePicker在Mozilla的東西,但我相信這將需要一些特殊權限(就像是瀏覽器本身的一部分)可能有可能。

+0

可能確實,並且不需要特殊權限..請參閱:http://jsfiddle.net/YhdSC/1/(僅限IE:/) – 2010-12-16 09:53:50

+0

是的,權限部分是關於Firefox的。 – 2010-12-16 14:58:04

7

有一些JavaScript庫通過小型嵌入式SWF文件實現了這種功能。例如this one

+1

這在我看來更多的是對這個問題的回答。我的意思是,它幫助了我,併爲此感謝:) – 2012-02-28 23:14:12

3

我發現了一個簡單的解決方案在這裏:http://www.codingforums.com/archive/index.php/t-181561.html

My text area:<br /> 
<textarea rows='10' cols='80' id='myTextArea' ></textarea> 

<br /><br /> 

Download button: <br /> 
<input value='download' type='button' 
onclick='doDL(document.getElementById("myTextArea").value)' /> 


<script type='text/javascript'> 
function doDL(s){ 
    function dataUrl(data) {return "data:x-application/text," + escape(data);} 
    window.open(dataUrl(s)); 
} 
</script> 

希望這將有助於。

21

這可能是你在找什麼: http://thiscouldbebetter.wordpress.com/2012/12/18/loading-editing-and-saving-a-text-file-in-html5-using-javascrip/

它使用瀏覽器的下載對話,但現在只支持FF和鉻,也許更多的瀏覽器?


編輯:

至於評論,我會在文章中嵌入代碼:

function saveTextAsFile() 
{ 
    var textToWrite = //Your text input; 
    var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'}); 
    var fileNameToSaveAs = //Your filename; 

    var downloadLink = document.createElement("a"); 
    downloadLink.download = fileNameToSaveAs; 
    downloadLink.innerHTML = "Download File"; 
    if (window.webkitURL != null) 
    { 
     // Chrome allows the link to be clicked 
     // without actually adding it to the DOM. 
     downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob); 
    } 
    else 
    { 
     // Firefox requires the link to be added to the DOM 
     // before it can be clicked. 
     downloadLink.href = window.URL.createObjectURL(textFileAsBlob); 
     downloadLink.onclick = destroyClickedElement; 
     downloadLink.style.display = "none"; 
     document.body.appendChild(downloadLink); 
    } 

    downloadLink.click(); 
} 
3

完全可以利用這種跨瀏覽器的JavaScript實現HTML5 saveAs功能:https://github.com/koffsyrup/FileSaver.js

如果你想要做的只是保存文本,那麼上面的腳本工作在所有瀏覽器(包括IE的所有版本)中,不需要SWF。

相關問題