Help us understand the problem. What is going on with this article?

HTML5上のJavaScript(async/await, response)を利用したファイル出力/読み込み

More than 1 year has passed since last update.

Introduction

Browser用JavaScriptによるファイルアップロード/ダウンロード方法を紹介.

サンプルファイルはJSONとする.

Related Articles

  1. JavaScriptでJSONファイルダウンロード by Qiita

  2. Export JSON to CSV file using Javascript (in the browser)

  3. HTML5 FileReader how to return result?(using jQuery)

Previous Methods

Export

出力はlocation.hrefapplication/jsonを仕込む.

const items = JSON.stringfy('[:anyJSONItems]', null, '\t');
const blob = new Blob([items], { type: 'application/json' });

location.href = URL.createObjectURL(blob);

Import

読み込みはFileReaderを利用.

function readFileModule(file, anyCallbackFunc) {
    const reader = new FileReader();

    reader.onload = e => {
      const result = e.target.result;
      const json = JSON.parse(result);
      anyCallbackFunc(json);
    };

    reader.readAsText(file);
};


const fileObj = document.querySelector("#select-file");

fileObj.addEventListener('change', async evt => {
    const file = evt.target.files[0];

    readFileModule(file, json => {
        console.log('# result json', json)
    });
},false);

Proposal Methods

Export

Blobaタグ(<a></a>)を利用する.

Import

async/awaitResponseを使う.

sample code

IO.js
const fileName = 'foo_bar.json'

export default {
  import: async file => {
    if (!file) return

    const response = await new Response(file)
    const jsonText = await response.text() // テキスト化
    return JSON.parse(jsonText)
  },
  export: items => {
    const jsonText = JSON.stringfy(items, null, '\t');
    const blob = new Blob([jsonText], { type: 'application/json;' })

    const _link = document.createElement('a') // aタグ作成
    if (_link !== undefined) {
      const url = URL.createObjectURL(blob)
      _link.setAttribute('href', url)
      _link.setAttribute('download', fileName) // ダウンロードさせるためには`download`属性が必須
      _link.style.visibility = 'hidden' // ブラウザ上には表示しない.
      document.body.appendChild(_link) // 一時的に`<body>`に追加
      _link.click() // aタグクリック
      document.body.removeChild(_link) // 削除
    }
  }
}
app.js
import $IO from './IO.js'

// import
const fileObj = document.querySelector("#select-file");

fileObj.addEventListener('change', async evt => {
    console.log('# importing...')
    const file = evt.target.files[0];
    const json = await $IO.import(file)
    console.log('# result json', json)
    console.log('# imported!')
},false);

// export 
const exportBtn = document.querySelector("#export-btn");

exportBtn.addEventListener('click', async evt => {
    console.log('# exporting...')
    await $IO.export(items)
    console.log('# exported!')
}, false);

References

  1. Using Promises with FileReader

  2. Error using async and await with filereader

hiyoko3
A Software developer in Tokyo.
https://hiyoko3.github.io/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away