LoginSignup
65
66

More than 5 years have passed since last update.

javascriptで生成したファイルをローカルに保存する

Last updated at Posted at 2012-12-26

a要素のdownload属性にファイル名を付けるとそのファイル名でダウンロードされます。

ブラウザ対応状況: https://caniuse.com/#feat=download

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');
65
66
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
65
66