question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Tracking progress when uploading files

See original GitHub issue

Is it possible to listen to the upload progress event given by the xhr object?

Normally it is done like this:

xhr.upload.addEventListener('progress', handler);

I know that the xhr object is returned by end() and in the response object. The latter fires only when the response is received though (which makes sense).

Any ideas?

Issue Analytics

  • State:closed
  • Created 9 years ago
  • Comments:12 (3 by maintainers)

github_iconTop GitHub Comments

30reactions
rexxarscommented, Mar 21, 2016

Yes. superagent fires progress events through it’s eventemitter.

Basically:

request
   .post('/api/file')
   .send(someFile)
   .on('progress', function(e) {
      console.log('Percentage done: ', e.percent);
   }
   .end(function(res){
     if (res.ok) {
       alert('yay got ' + JSON.stringify(res.body));
     } else {
       alert('Oh no! error ' + res.text);
     }
   });

See https://github.com/visionmedia/superagent/blob/master/lib/client.js#L756-L770

5reactions
alexsasharegancommented, Feb 24, 2017

@similityman Alternative to @teonik’s solution, you can use a bound function (arrow function) when attach the superagent onprogress handler. This can also give you a chance to bind extra params to your onprogress handler if you need references to anything.

// without extra params
req.on( 'progress', event => this.onProgress( event ) );

// with extra reference to the files array
req.on( 'progress', event => this.onProgress( event, files ) );

I personally chose to fire off individual requests for each file upload in my own app so I could render progress per file. I used the second method to bind a uuid to each file so I could map the progress emitted to the correct file in the uploading queue. Not sure how valuable copy/pasting that example will be, but hey… sharing is caring!

// from inside my Uploader component wrapping DropZone...
/**
 * Proxied handler function for the DropZone's native 'onDrop' method.
 * Called with an array of files uploaded.
 * Sets up component state to handle progress bars,
 * and uses uuid's to make unique keys on potential
 * files with identical names.
 *
 * @param files
 */
uploadFiles( files ) {
    const filesToUpload = files.map( ( file ) => {
        return { name: file.name, percent: 0, uuid: uuid.v4(), timestamp: Date.now(), data: file };
    } );
    
    this.setState( {
        isUploading: true,
        files: [ ...this.state.files, ...filesToUpload ],
    } );
    
    let promises = filesToUpload.map( file => this.uploadFile( file ) );
    
    Promise.all( promises ).then( () => {
        this.setState( { isUploading: false } );
        this.onUploadComplete();
    } );
}

/**
 * By attaching each file to an individual ajax call,
 * we are able to bind our unique keys to the progress events
 * and render progress on each individual file.
 *
 * @param file
 * @returns {Promise}
 */
uploadFile( file ) {
    return (
        request.post( this.props.uploadURI )
               .attach( file.name, file.data )
               .on( 'progress', ( event ) => this.onUploadProgress( file.uuid, event.percent ) )
    );
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Uploading files with progress monitoring in VanillaJS, Angular ...
So, in this post we will see how to upload files asynchronously with JavaScript with progress monitoring. Step 1: Our backend. Yes, we...
Read more >
File upload progress bar with jQuery - Stack Overflow
I've done this with jQuery only: $.ajax({ xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function(evt) ...
Read more >
Tracking file upload progress using axios - gists · GitHub
Tracking file upload progress using axios. GitHub Gist: instantly share code, notes, and snippets.
Read more >
Adventures in Tracking Upload Progress With OkHttp and ...
This article tells the story of how Stream's Android team refined our progress tracking process during file uploads in the Stream Chat ...
Read more >
Tracking Upload Progress in Browsers | Siaw Young
loaded, evt.total]); }); } }} > Upload file </button> <input type="file" name="myfile" onChange={e => { if (e.target.files && e.target.files.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found