2016-02-29 2 views
0

У меня есть загрузка нескольких файлов, и я хотел бы показать процент загрузки. В JavaScript У меня есть этот код:Загрузить MultipartFile с процентом

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) { 
     .... 
    } 
} 

и используя MultipartFiletransferTo метод, который я загрузить файл. Я прочитал несколько руководств, но все для подачки, возможно ли интегрировать процентный прогресс в моем коде? Я использую этот код как для веб-страницы, так и для вызова REST от клиента, и с помощью этого метода я не получаю сообщение об ошибке.

+1

Я использовал «OnProgress» событие для отображения информации. Вот ссылка, в которой объясняется, как использовать ее с jQuery: [JQuery ajax progress] (http://www.dave-bond.com/blog/2010/01/JQuery-ajax-progress-HMTL5/) – Roberto

+0

благодарит за работу , – luca

+0

Luca, а как насчет ответа на свой вопрос? –

ответ

0

Это как мой код теперь, чтобы показать прогресс бар:

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: функция(), как @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); 
Смежные вопросы