11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

superagentでajaxでファイルのアップロードで進捗状況を取得する

Last updated at Posted at 2015-08-28

ファイルのアップロードをajaxを使って非同期で行う時に、ファイルアップロードの進捗状況を取得したいです。
jQueryや素のHttpRequestを使ったサンプルは多くあるのですが、superagentを使ったサンプルは少ないです。これはそのメモです。

HTMLはこのようなものを用意します。

<input type="file" id="myfile" />

superagentからは次のようにして取得します。(ES6の記法で書いています)

import request from 'superagent';

file_field = document.getElementById('myfile')[0];
request.post('/api/file')
  .attach("attachment", file_field.files[0])
  .on('progress', (evt)=> {
    console.debug(evt.percent);
  }).end((err, res) -> {
    if (err) {
      console.error(err);
    }
    console.info(res);
  });

onでprogessのイベントを補足して、進捗状況をコンソールに出力しています。eventオブジェクトは全体量を表すtotalとアップロードした分量を表すloadedがありますが、superagentをついでに全体の進捗状況をパーセントで取得できるようになっています。普通はパーセントで進捗状況を表したいので、何気に便利です。

11
13
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
11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?