LoginSignup
3
6

More than 3 years have passed since last update.

WebからFetch APIで取得したファイルをJavaScriptのFileオブジェクトとして扱う方法

Posted at

概要

JavaScriptのFetch APIをつかってWebからファイルをダウンロードしてきて、それをFileオブジェクト として扱う方法

やり方

const path="https://riversun.github.io/img/riversun_144.png";

fetch(path)
    .then(res => {
        return res.blob().then(blob => ({
            contentType: res.headers.get("Content-Type"),
            blob: blob
        }));
    })
    .then(data => {
        return new File([data.blob], path, {type: data.contentType});
    })
    .then(file => {
        //ここでfileを扱うコードを書く
    });

ポイント

  • res.blob()メソッドでレスポンスからBlobデータとして読み込むが、このメソッドはPromiseを返す
  • ついでに、ヘッダーから"Content-Type"を読み出したいが、無邪気に以下のようにするとスコープ外なのでresにアクセスできない

 fetch(path)
     .then(res => {
         return res.blob();
     })
     .then(blob => {
         //blobは取得できたけど、resから"Content-Type"ヘッダを取り出せない・・・
     })
  • 以下のようにresが同一スコープになるようblob()から下位になるようチェインして、Content-Typeまで取得してから次に渡す。
return res.blob().then(blob => ({
    contentType: res.headers.get("Content-Type"),
    blob: blob
}));
3
6
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
3
6