2

I've created a HTML form element as below for file uploading. And currently the file can be uploaded to server correctly.

<form id="file_upload_form" action="http://localhost:8000/v1/file?op=upload" enctype="multipart/form-data" method="post">
    <input type="file" name="xxx">
    <input type="submit" value="Send">
</form>

I want to get the file upload progress by pure jQuery/JS. And I got some code as below to achieve it from my research.

$("#file_upload_form").submit(function(){
    console.log("here");
    var xhr = new XMLHttpRequest();
    xhr.upload.addEventListener( "progress", function ( evt )
    {
        if( evt.lengthComputable )
        {
            var progressPercent = ( evt.loaded / evt.total ) * 100;
            console.log( progressPercent );//your function.
        }
    }, false );
});

But the program never run into the EventListener. Is it possible to get the file upload progress by pure jQuery/JS for my HTML form?

ybdesire
  • 1,593
  • 1
  • 20
  • 35
  • Check this http://stackoverflow.com/questions/15410265/file-upload-progress-bar-with-jquery – Kavin Sep 06 '15 at 08:07
  • Thanks @Kavin for the suggestion. I've checked this link before asking the question. Their answer not work for my situation. Would you provide some suggestion based on my code here? – ybdesire Sep 06 '15 at 09:29

1 Answers1

0

Well, it looks like you never actually upload data, so the program never run into the EventListener. Try something like this:

$.ajax({
  xhr: function()
  {
    var xhr = new window.XMLHttpRequest();
    //Upload progress
    xhr.upload.addEventListener("progress", function(evt){
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with upload progress
        console.log(percentComplete);
      }
    }, false);
    //Download progress
    xhr.addEventListener("progress", function(evt){
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with download progress
        console.log(percentComplete);
      }
    }, false);
    return xhr;
  },
  type: 'POST',
  url: "/",
  data: {},
  success: function(data){
    //Do something success-ish
  }
});

Learn more here: JQuery ajax progress

Maxim Mazurok
  • 3,856
  • 2
  • 22
  • 37
  • 1
    Thanks @Maxim. My form element can upload file into server side correctly. The file selected by form can be posted to server directly, and I don't need to touch the file data. But your solution seems we need to get the file data, and the file data is sent by this ajax POST, not by form POST. I just want to POST data by form element. Do you know if wen can get the form POST progress(not ajax POST progress)? – ybdesire Sep 07 '15 at 01:21