環境
・ES2015(ES6)・Babelでコンパイルして動作させています。
・Axiosでファイルを取得
やりたいこと
サーバーサイド側でcsv等を出力した際にファイル名を設定されている場合は、そのファイル名を取得したい。
フロントエンドでゴニョゴニョも出来るけど、まあ望ましくないのできちんと取得するのです。
ファイル名を取得する関数
ファイル名はcontent-dispositionに格納されるので、そいつを抜き出してあげましょう。
なお、他の情報もあるセミコロン区切りの文字列なので正規表現等で頑張る必要があります…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public static getFileNameFromContentDisposition(disposition) { const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; // 正規表現でfilenameを抜き出す const matches = filenameRegex.exec(disposition); if (matches != null && matches[1]) { const fileName = matches[1].replace(/['"]/g, ''); return decodeURI(fileName) // 日本語対応 } else { return null } import axios from 'axios' axios({ url: 'http://api.dev/file-download', method: 'GET', // POSTでもok responseType: 'blob', // これがないと文字化けする }).then((response) => { const contentDisposition = response.headers['content-disposition']; const fileName = getFileNameFromContentDisposition(contentDisposition); // 別記事で作った関数 downloadCsvBlob(response.data, fileName) }); } |
※dowloadCsvBlobはこちらの記事で作ったファイルダウンロード用の関数です。・
最近JavaScript関連の記事ばかりですね。まあ悩むことが多いのはこっちの方なので致し方なし。
フロントエンドは出来ることと、想定する幅が広くて色々大変。