【问题标题】:Progress bar for an image upload with jQuery $.ajax and Spring Boot使用 jQuery $.ajax 和 Spring Boot 上传图片的进度条
【发布时间】:2018-01-06 19:41:49
【问题描述】:

我在 $.ajax 帖子中设置进度条时遇到问题,该帖子通过带有 Spring 框架的 @Controller 将图像上传到 Cloudinary 服务。我的问题是监控上传过程的事件从一开始就上传了整个文件。

ProgressEvent {isTrusted: true, lengthComputable: true, loaded: 8718, total: 8718,
type: "progress"…}

这是我的代码:

 var token = $("meta[name='_csrf']").attr("content");
 var header = $("meta[name='_csrf_header']").attr("content");
 $.ajaxSetup({
      beforeSend: function(xhr){
          xhr.setRequestHeader(header, token);
     }
 });
 /*<![CDATA[*/
 for(var i = 0; i < filesList.length; i++){
  /*]]>*/
       var formData = new FormData();
       formData.append("file", filesList[i]);
          $.ajax({
              xhr: function()
                 {
                  var xhr = $.ajaxSettings.xhr();
                  //Upload progress
                  xhr.upload.addEventListener("progress", function(event){

                      if (event.lengthComputable) {
                          var percentage = Math.round((event.loaded *100) / event.total);

                          $(".progress-bar").css("width", percentage + "%");
                      }
                  }, false);
                  return xhr;
                  },

              url:  "/admin/web/cms/upload",
              type: "POST",
              contentType: false,
              processData: false,
              data: formData,

              success: function(data) {
                 $(".progress-bar").css("width", "0%");
              }
         });
         console.log(filesList[i].size);
  }

因此,进度条始终显示为已完成。 我该如何管理,监控图像上传过程,用进度条显示它? 任何帮助将非常感激。提前谢谢你。

【问题讨论】:

  • 你找到解决办法了吗?
  • 是的,但采用完全不同的方法。我已经发布了对我有用的代码摘录。我建议您查看 Cloudinary 文档,了解功能 cloudinary_fileupload。

标签: jquery spring cloudinary


【解决方案1】:

解决方案是那个,带有cloudinary_fileupload 函数:

 $(".cloudinary-fileupload").cloudinary_fileupload({

  ...

     progressall: function(e, data){
          $(".progress-bar").width(Math.round((data.loaded * 100.0) / data.total) + "%");
          $(".progress-bar").text(Math.round((data.loaded * 100.0) / data.total) + "%");

          if((Math.round((data.loaded * 100.0) / data.total) === 100) && filesAmount > -1){
                 $(".progress-bar").text('');
                 $("#uploading").text(processingImatges);
                 $(".progress-bar").addClass("progress-bar-striped progress-bar-animated");

                         $(window).bind('beforeunload', function(){ 
                         return processingImatges;
                 });
          }
      },

使用这种方法,进度条会同时监控正在上传的所有图像,而不是每一张。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    相关资源
    最近更新 更多