fetchで取得したファイルをダウンロードする
fetchで取得したファイルをダウンロードする方法を紹介します。
レスポンスヘッダのContent-Dispositionの情報からダウンロードファイルの有無やファイル名を取得します。
ファイルがある場合はファイルダウンロードを行うためのaタグを内部的に作成し、そのaタグのクリック処理を行います。
const response = await fetch('/test/download');
const disposition = response.headers.get('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
const fileName = decodeURIComponent(matches[1].replace(/['"]/g, ''));
const a = document.createElement('a');
a.href = window.URL.createObjectURL(await response.blob());
a.download = fileName;
a.click();
}
}