LoginSignup
3
5

More than 5 years have passed since last update.

文字列等のデータをファイルとしてダウンロードさせる関数

Last updated at Posted at 2015-09-16

必要になったので書いてみました。
Google Chromeのコンソールで使うために書いたので、それ以外の環境での動作は保証しません。

/**
 * @param {ArrayBuffer|ArrayBufferView|Blob|string} content ダウンロードさせるデータ
 * @param {string=} filename ファイル名。省略可
 * @param {string=} mimetype データのMIME Type。省略可
 * @see http://furudate.hatenablog.com/entry/2014/06/02/172923
 */
function downloadData(content, filename, mimetype) {
    if (arguments.length < 3) {
        mimetype = 'application/octet-stream';
    }

    var url = (window.URL || window.webkitURL).createObjectURL(new Blob([content], { 'type': mimetype }));
    var a = document.createElement('a');

    a.target = '_blank';
    a.download = filename || '';
    a.href = url;

    a.click();
}
3
5
5

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
3
5