LoginSignup
1
0

More than 1 year has passed since last update.

ajaxでファイルダウンロード

Last updated at Posted at 2021-06-08

jqueryでshiftjisでできたファイルのダウンロードのやり方。
$ajaxだとうまくいかなかったけどこれならうまくいった


fetch(url, {method: 'GET'})
           .then((res) => {
                if (!res.ok) {
                    throw new Error(`${res.status} ${res.statusText}`);
                }
                return res.blob();
            })
            .then((blob) => {
                const url = URL.createObjectURL(blob);
                const a = document.createElement("a");
                document.body.appendChild(a);
                a.download = filename;
                a.href = url;
                a.click();
                a.remove();
                setTimeout(() => {
                    URL.revokeObjectURL(url);
                }, 1E4);
            })
            .catch((reason) => {
                console.error(reason);
                alert('予期せぬエラーが発生しました。');
            });

1
0
0

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
1
0