Skip to content

Instantly share code, notes, and snippets.

@ukyo
Last active February 15, 2018 05:42
Show Gist options
  • Save ukyo/1753046 to your computer and use it in GitHub Desktop.
Save ukyo/1753046 to your computer and use it in GitHub Desktop.
javascriptで生成したファイルをローカルに保存する ref: https://qiita.com/ukyo/items/d623209655a003b13add
function download(blob, filename) {
const objectURL = window.URL.createObjectURL(blob),
a = document.createElement('a'),
e = document.createEvent('MouseEvent');
//a要素のdownload属性にファイル名を設定
a.download = filename;
a.href = objectURL;
//clickイベントを着火
e.initEvent("click", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
}
//使用例
download(new Blob(['hello world']), 'hello.txt');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment