【问题标题】:Upload MultipartFile with percentage上传带百分比的 MultipartFile
【发布时间】:2016-02-29 08:08:07
【问题描述】:

我有几个文件上传,我想显示上传百分比。 在javascript中我有这个代码:

function uploadFunction(fileType){
    //CSRF attribute for spring security
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");

    var formData = new FormData();
    var fileControl = document.getElementById(fileType);
    var length = fileControl.files.length;
    for(var i = 0; i< length; i++){ 
        formData.append('file[]',fileControl.files[i]); 
    } 
    formData.append('idFleet', selectedFleet);
    formData.append('idCar', $("#selectedCar").val());
    if(fileType!='dat')
        formData.append('initialKm', 0);
    else
        formData.append('initialKm', $("#initialKm").val());
    return jQuery.ajax({
        url : 'upload',
        type: 'POST',
        contentType: false,
        processData: false,
        data:formData,
        beforeSend:function(xhr) {
            xhr.setRequestHeader(header, token);
            waitingModal.showPleaseWait();
        },  
        success: function(data,status,xhr){
            //No exception occurred
            if (data.status){   
                //Also the field are right(for e.g. form value)
                if(data.success){
                    //Store information if file is datatable
                    if (fileType=='datatable')
                        $("#datatablePath").val(data.result[0]);
                    notifyMessage(fileType + " has been uploaded!", 'success');
                    uploadResult=true;
                }
                else{
                    //code if there are some error into form for example
                }
            } else {
                notifyMessage(data.result, 'error');
                $('#acquisitionWizard').bootstrapWizard('show',2);//show
                uploadResult=false;
            }
        },
        error: function(xhr,status,e){
            window.location.href = "/DART/500";
        }
    }).complete(function() {
        //add timeout because otherwise user could see a too fast waiting modal
        setTimeout(function(){
            waitingModal.hidePleaseWait();
        }, 1000);
    });

}

在春天我有

@Override
@RequestMapping(value = { "/upload"}, method = RequestMethod.POST)
public @ResponseBody Response uploadFiles(Principal principal, @RequestParam("file[]") MultipartFile[] file, @RequestParam("idFleet") Integer idFleet, @RequestParam("idCar") Integer idCar, @RequestParam("initialKm") Integer initialKm) {
    try {
        ArrayList<String> path=fleetAcquisitionServices.uploadFiles(principal.getName(), file, idFleet, idCar, initialKm);
        return new Response(true,true,path,null);
    } catch (FileEmptyException e) {
        ....
    }
}

并使用MultipartFile transferTo 方法上传文件。 我阅读了一些指南,但都是针对 serverlet 的,是否可以在我的代码中集成百分比进度? 我在网页和来自客户端的 REST 调用中都使用此代码,并且使用此方法我不会收到有关内存的错误。

【问题讨论】:

  • 我使用了“onprogress”事件来显示信息。这是一个解释如何将它与 jQuery 一起使用的链接:JQuery ajax progress
  • 卢卡,回答你自己的问题怎么样?
  • 对不起,我写的代码是正确的。

标签: javascript jquery ajax spring upload


【解决方案1】:

这就是我的代码现在显示进度条的方式:

function uploadFunction(fileType){
    //CSRF attribute for spring security
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");

    var formData = new FormData();
    var fileControl = document.getElementById(fileType);
    var length = fileControl.files.length;
    for(var i = 0; i< length; i++){ 
        formData.append('file[]',fileControl.files[i]); 
    } 
    formData.append('idFleet', selectedFleet);
    formData.append('idCar', $("#selectedCar").val());
    if(fileType!='dat')
        formData.append('initialKm', 0);
    else
        formData.append('initialKm', $("#initialKm").val());
    return jQuery.ajax({
        url : 'upload',
        type: 'POST',
        timeout: 0,//unlimited timeout
        contentType: false,
        processData: false,
        data:formData,
        //Catch upload progress
        xhr: function()
          {
            var xhr = new window.XMLHttpRequest();
            //Upload progress
            xhr.upload.addEventListener("progress", function(evt){
              if (evt.lengthComputable) {
                var progress = Math.round((evt.loaded / evt.total) * 100) + '%';
                //Update progress bar and text
                document.getElementById("fileProgressBar").style.width = progress;
                document.getElementById("percentualFile").innerHTML = progress;
              }
            }, false);
            return xhr;
          },
        beforeSend:function(xhr) {
            xhr.setRequestHeader(header, token);
            waitingFile.showPleaseWait();
        },  
        success: function(data,status,xhr){
            //No exception occurred
            if (data.status){   
                //Also the field are right(for e.g. form value)
                if(data.success){
                    //Store information if file is datatable
                    if (fileType=='datatable')
                        $("#datatablePath").val(data.result[0]);
                    notifyMessage(fileType + " has been uploaded!", 'success');
                    uploadResult=true;
                }
                else{
                    //code if there are some error into form for example
                }
            } else {
                notifyMessage(data.result, 'error');
                $('#acquisitionWizard').bootstrapWizard('show',2);//show
                uploadResult=false;
            }
        },
        error: function(xhr,status,e){
            window.location.href = "/DART/500";
        }
    }).complete(function() {
        //add timeout because otherwise user could see a too fast waiting modal
        setTimeout(function(){
            //Reset to 0 progress bar and text
            document.getElementById("fileProgressBar").style.width = "0%";
            document.getElementById("percentualFile").innerHTML = "0%";
            waitingFile.hidePleaseWait();
        }, 1000);
    });

}

我介绍了 xhr: function() @Roberto 在他的回答中的建议。 下载进度状态可以使用类似的函数

//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);

【讨论】:

    猜你喜欢
    • 2011-08-17
    • 2016-05-04
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    相关资源
    最近更新 更多