如何透過 javascript 產生下載檔案的功能
how to download text files via javascript
var textToSave = 'this is a test';
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:attachment/text,' + encodeURIComponent(textToSave);
hiddenElement.target = '_blank';
hiddenElement.download = 'myFile.txt';
hiddenElement.click();
上面的範例,如果是使用 encodeURI
很容易遇到內容跳脫的問題,例如:內容有# 就掛了,檔案內容很容易被中斷,建議使用 encodeURIComponent
。
這2者的差別:
>>> encodeURI("bla&bla&bla")
"bla&bla&bla"
>>> encodeURIComponent("bla&bla&bla")
"bla%26bla%26bla"
>>> encodeURI('[{"id":1,"href":"#"}]')
%5B%7B%22id%22:1,%22href%22:%22#%22%7D%5D
>>> encodeURIComponent('[{"id":1,"href":"#"}]')
%5B%7B%22id%22%3A1%2C%22href%22%3A%22%23%22%7D%5D
差異在 # encodeURI 時還是 #, encodeURIComponent 變成 %3A
下載 svg 圖片的範例:
const svgBlob = new Blob([svgData], {
type: "image/svg+xml;charset=utf-8",
});
const objectUrl = URL.createObjectURL(svgBlob);
const downloadLink = document.createElement("a");
downloadLink.href = objectUrl;
downloadLink.download = filename;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);