Progress bar for superagent file upload

2019-05-29 17:02发布

问题:

I am using the following codes to upload files. File would be sent through superagent in blob format, convert it to dataURI when reaches server and save into AWS S3.

files.forEach((file) => {
  superagent.post('http://localhost:3030/uploads')
  .attach('file', file)
  .on('progress', e => {
    console.log('Percentage done: ', e);
  })
  .end((err, res) => {
    // console.log(err);
    console.log(res);
  });
});

File upload works but the progress bar is not populated correctly.

As per the screenshot, you can see that the ProgressEvent upload percentage ended very fast at 100%, due to both frontend and backend hosted in a same server.

The upload progress continued in the background but the direction became "download" instead of "upload" from 14:14:08 to 14:14:14 and completed with a response.

I could not calculate the progress based on "total - loaded" too, because during the "download" progress, the total is 0.

Tried replacing superagent with axios and hit the same problem.

files.forEach((file) => {
  const url = 'http://localhost:3030/uploads';
  const formData = new FormData();
  const config = {
    headers: {
      'content-type': 'multipart/form-data'
    },
    onUploadProgress: e => {
      console.log('Upload: ', e);
    },
    onDownloadProgress: e => {
      console.log('Download: ', e);
    }
  };
  formData.append('file', file);
  axios.post(url, formData, config)
    .then(res => console.log(res))
    .catch(err => console.log(err));
});

How could I build a progress bar out of it? Can I conclude that the "upload" is the process of uploading to the server, while "download" is the process of uploading to AWS?

回答1:

today I met this problem(so I'm writing in this topic...) Docs https://visionmedia.github.io/superagent/ clearly says, that

event is direction: "upload" or "download"

So IMHO you have to do something like:

        if(event.direction === "upload")
            console.log(e.direction,"is done",e.percent,"%")})

and it works so can setState() for progress bar here. It's very dummy, but well. https://visionmedia.github.io/superagent/docs/test.html also here they are using this. Does anyone has better idea for this?