jQuery fileupload plugin success call back

旧时模样 提交于 2020-01-05 07:30:36

问题


I used the jQuery File Upload Plugin (https://github.com/blueimp/jQuery-File-Upload) to upload multiple pictures simultaneously in rails. The photo is attached to the Item model, and item is added to a poll.

Using the plugin as:

$(document).ready(function(){
    $('#fileupload').fileupload({
      url: '/polls',
      dataType: "json",
      done: function(e,data){
        window.location = "/polls/" + data.result.id;
      }
    }
});

It was expected to call the create action in the Poll Controller for each photo file and redirect the page to show the created poll after all the files were uploaded. However, for instance, when 6 files were chosen to upload, it only displayed 4 photos in the poll page at first. After refreshing the page, it displayed 6 photos. I guessed the issue was caused by the call-back function. Seems it redirected to the poll page before the uploading of all the files
were done. All the upload requests should be sent successfully, but the items were not all created (it may take seconds for paperclip to process the images).

Any suggestions for me to solve this issue? Thanks

Edit: Checked that the "done" call-back function actually was called for each successful http request. It was not called after all the requests were sent. And the create action was called for each photo file. How can I have a function that will call back only after the all files were uploaded, either on client side or server side?


回答1:


The done callback acts like the success callback sent by jQuery ajax() it does not mean the the file upload has been completed. Try using

$('#fileupload').bind('fileuploaddone', function (e, data) {/* ... */})

I'm not sure if the above would work but give it a try. If that doesn't you could always write a method on the server side to report back when the upload is done.




回答2:


You could try using the add callback to count the files being uploaded and then decrement that number on each done callback. Then you would only do the redirect if that number was 0.

Something like this:

$(document).ready(function(){
    var filesToProcess = 0;
    $('#fileupload').fileupload({
      url: '/polls',
      dataType: "json",
      add: function(e, data){
        filesToProcess++;
      },
      done: function(e,data){
        filesToProcess--;
        if (filesToProcess === 0){
          window.location = "/polls/" + data.result.id;
        }
      }
    }
});



回答3:


There is another callback "stop" which is fired when all the files are uploaded. Try that instead



来源:https://stackoverflow.com/questions/13558389/jquery-fileupload-plugin-success-call-back

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!