透過 JQuery 產生 .txt 檔案,並且下載

  • 2251
  • 0

最近有一些需求,必須要產生一個 .txt 檔案給客戶下載,當然我也可以送回 server 產生好然後設定好 MIME 讓客戶下載,但是這樣除了麻煩還耗地球資源,所以下文就容許我廢話紀錄一下..


上面你已經看到 Code 了 其實重點再 IE 處理比較麻煩,要對 iframe 下指令 :

 

                    jQuery('<iframe/>', {
                        id: 'tmpIframe', width: 10, height: 10
                    }).appendTo('body');
                    
                    $('#tmpIframe')[0].contentWindow.document.open('text/plain', 'replace');
                    $('#tmpIframe')[0].contentWindow.document.write(str);
                    $('#tmpIframe')[0].contentWindow.document.close();
                    $('#tmpIframe')[0].contentWindow.document.execCommand('SaveAs', true, '網站資訊.txt');

                    $("#tmpIframe").remove();


一般狀況下設定 href , download 就可以了,這很簡單 就直接提供原始碼就不贅述了…

reference :
https://stackoverflow.com/questions/25121384/ie-download-file
https://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery

 

---

 

請你暫時把你的勇氣給我 在夢想快消失的時候 讓我的 Code 用力的穿過天空 為愛我的人做一秒英雄 如果這篇文章有幫助到您,簡單留個言,或是幫我按個讚,讓我有寫下去的動力...