File Upload Progress Tips

Keywords: Javascript JQuery SDK Programming

demand

When the uploaded files are relatively large, users may need to wait for a long time. At this time, if there is no prompt on the front end, the experience is not very good. If there is a prompt on the upload progress, it will be much better. In order to display the upload progress in real time during the upload process, the uploaded size and the total file size are required.

premise

  • The request is asynchronous. For real-time access to upload progress, the request needs to be asynchronous, and if synchronous, the response will not be available until the request is completed.

Realization

The main summary here is the js aspect. As for the display of the progress bar, some UI frameworks, such as semantic, have their own implementation of the progress bar, which can be used directly. If not, they can also be implemented by changing the width of the div themselves. This is not to be discussed here.

How to get the upload progress of files?
Javascript's XMLHttpRequest provides a progresses event that returns the size and total size of the uploaded file. Based on these two values, the upload progress can be calculated. This method is described in Chapter 21, Section 3, of Javascript Advanced Programming (3rd Edition). This book is available at hand. Once. Next, paste the code.

XMLHttpRequest: programs events

Using Javascript's XMLHttpRequest's progress es event, the sample code is implemented as follows:

var formData = new FormData(); 
formData.append("file", document.getElementById('file').files[0]); 
formData.append("token", token_value); // Other parameters are added in this way

var xhr = new XMLHttpRequest();
xhr.open('POST', '/uploadurl');
// Callback function after uploading
xhr.onload = function () {
  if (xhr.status === 200) {
  console.log('Upload Success');
  } else {
   console.log('Upload error');
  }
};
// Get upload progress
xhr.upload.onprogress = function (event) {
  if (event.lengthComputable) {
    var percent = Math.floor(event.loaded / event.total * 100) ;
    // Set up progress display
    $("#J_upload_progress").progress('set progress', percent);
  }
};
xhr.send(formData);

For FormData and XMLHttpRequest, you can search W3C for details.

xhr encapsulated in jQuery

JQuery encapsulates the implementation of xhr, and can also use jQuery's ajax to get upload progress. Sample code:

var formData = new FormData(); 
formData.append("file", document.getElementById('file').files[0]); 
formData.append("token", token_value); 

$.ajax({ 
    url: "/uploadurl", 
    type: "POST", 
    data: formData, 
    processData: false, // Do not serialize data parameters, default to true
    contentType: false, // Do not set the Content-Type request header because the file data is encoded in multipart/form-data
    xhr: function(){
        myXhr = $.ajaxSettings.xhr();
        if(myXhr.upload){
          myXhr.upload.addEventListener('progress',function(e) {
            if (e.lengthComputable) {
              var percent = Math.floor(e.loaded/e.total*100);
              if(percent <= 100) {
                $("#J_progress_bar").progress('set progress', percent);
                $("#J_progress_label". HTML ('uploaded:'+percent+'%');
              }
              if(percent >= 100) {
                $("#J_progress_label". HTML ('File upload is complete, please wait for...');
                $("#J_progress_label").addClass('success');
              }
            }
          }, false);
        }
        return myXhr;
    },
    success: function(res){ 
        // Successful request
    },
    error: function(res) {
        // request was aborted
        console.log(res);
    }
}); 
 

For xhr of jQuery ajax, see W3C specifically.

Qiniuyun Storage

Some files are too large, the background will upload to Qiniu, and then get their address to save to the database. In this way, the front end can use the above two ways XMLHttpRequest or jQuery encapsulated xhr to send requests and obtain upload progress. If more complex upload data processing is needed, it can also consider making It is implemented with Javascript SDK provided by Qiniu. If only progress hints are needed, it is not necessary to introduce Qiniu JS SDK.

On the other hand, if you set up redirection to a page of the website after successful upload, you may miss cross-domain redirection.

Related links

Posted by agge on Tue, 16 Jul 2019 12:53:34 -0700