LoginSignup
0
4

More than 3 years have passed since last update.

FlaskとJavaScriptのFetch通信でダウンロードさせる方法

Posted at

はじめに

Flaskのレスポンスによってファイルをダウンロードさせる方法は以下のリンクのとおり3つあるようです。
https://qiita.com/5zm/items/760000cf63b176be544c

しかしながら、Fetch通信によるPOSTに対するresponseにはこれらの方法だけでは対応出来ませんでした。解決した方法を以下に載せておきます。

前提

①Fetch通信で、Flaskサーバに対しPOSTリクエスト
②Flaskサーバでデータを処理し、ファイルを生成、responseヘッダに添付
③Fetchでresponseを受け取って、ダウンロードしたい

③で引っかかっていました。単なるinputによるPOSTとは勝手が違うようで、responseはメモリ上で受けるだけです。

解決方法

    fetch("/export", {
        method:"POST",
        body:formdata //データを添付
    })
    .then(response => response.blob()) //blobで読み込む
    .then(blob => {
        //DOMでダウンロードファイルを添付したアンカー要素を生成
        let anchor = document.createElement("a");
        anchor.download = String(Date.now()) + '.geojson'
        anchor.href = window.URL.createObjectURL(blob);
        //アンカーを発火
        anchor.click();
    })
    .catch(function(err) {
        console.log("err=" + err);
    });

要はresponseをblobで読み込んでアンカーリンクを踏ませた事にするというわけですね。

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