LoginSignup
35

More than 3 years have passed since last update.

axiosでファイルダウンロード処理を実装(IEにも対応)

Last updated at Posted at 2019-08-01

ダウンロードの仕組みはブラウザにて実装状況が異なるようです。

File APIを使ったダウンロードの仕組みが有名ですが、
IEではwindow.URL.createObjectURL()を使用するとおかしくなるみたいです。

File APIのブラウザによる差を吸収してくれるfileSaverというライブラリがあるため、
そちらを使用するとIEでも問題なくダウンロードできるようになります。

fileSaver - GitHub

ダウンロード処理の例

import { saveAs } from "file-saver";
import axios from "axios";

function download(params = {}){
    axios.get(apiUrl, {
              params,
              responseType: "blob"
            })
            .then(response => {
              const blob = new Blob([response.data], {
                type: response.data.type
              });

              //レスポンスヘッダからファイル名を取得します
              const contentDisposition = response.headers["content-disposition"];
              const fileName = getFileName(contentDisposition)

              //ダウンロードします
              saveAs(blob, fileName);
    })
}

function getFileName(contentDisposition){
    let fileName = contentDisposition.substring(contentDisposition.indexOf("''") + 2,
                                                contentDisposition.length
                                                );
    //デコードするとスペースが"+"になるのでスペースへ置換します
    fileName = decodeURI(fileName).replace(/\+/g, " ");

    return fileName;
}

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
35