2013-11-14 17 views
6

Tôi muốn triển khai tệp tải lên trong ứng dụng web của mình, tôi đang sử dụng angular.js ở phía máy khách và spring mvc ở phía máy chủ.angularjs và spring mvc - tải lên nhiều tệp trong một yêu cầu

Tôi đã quản lý để tải lên một tệp và nhiều tệp tải lên hoạt động bằng cách sử dụng https://github.com/danialfarid/angular-file-upload. Có điều là, khi tôi upload nhiều file mỗi một trong số họ đang đến với tôi như yêu cầu riêng biệt (đó là sự kiện hiển nhiên sau khi đọc mã ví dụ):

//inject angular file upload directives and service. 
angular.module('myApp', ['angularFileUpload']); 

var MyCtrl = [ '$scope', '$upload', function($scope, $upload) { 
    $scope.onFileSelect = function($files) { 
    //$files: an array of files selected, each file has name, size, and type. 
    for (var i = 0; i < $files.length; i++) { 
     var $file = $files[i]; 
     $scope.upload = $upload.upload({ 
     url: 'server/upload/url', //upload.php script, node.js route, or servlet url 
     // method: POST or PUT, 
     // headers: {'headerKey': 'headerValue'}, withCredential: true, 
     data: {myObj: $scope.myModelObj}, 
     file: $file, 
     //(optional) set 'Content-Desposition' formData name for file 
     //fileFormDataName: myFile, 
     progress: function(evt) { 
      console.log('percent: ' + parseInt(100.0 * evt.loaded/evt.total)); 
     } 
     }).success(function(data, status, headers, config) { 
     // file is uploaded successfully 
     console.log(data); 
     }) 
     //.error(...).then(...); 
    } 
    } 
}]; 

có một lần lặp qua tất cả các tập tin.

Bây giờ tôi tự hỏi liệu có thể tải lên nhiều tệp như một yêu cầu duy nhất hay không.

Trả lời

1

vào mùa xuân khiển bên tạo

@RequestMapping(value = "/upload", method = RequestMethod.POST) 
    public String save(@ModelAttribute("filesForm") FileUploadForm filesForm) { 
       List<MultipartFile> files = filesForm.getFiles(); 
       //do something 

     } 


public class FileUploadForm 
    { 
    private List<MultipartFile> files; 

    // geters and setters ... 

    } 

về dịch vụ tải lên phía khách hàng

return { 
      send: function(files) { 
       var data = new FormData(), 
      xhr = new XMLHttpRequest(); 
       xhr.onloadstart = function() { 
        console.log('Factory: upload started: ', file.name); 
        $rootScope.$emit('upload:loadstart', xhr); 
       }; 

       xhr.onerror = function(e) { 
        $rootScope.$emit('upload:error', e); 
       }; 
       xhr.onreadystatechange = function(e) 
       { 
        if (xhr.readyState === 4 && xhr.status === 201) 
        { 
         $rootScope.$emit('upload:succes',e, xhr, file.name ,file.type); 

        } 
       }; 

     angular.forEach(files, function(f) { 
     data.append('files', f, f.name); 
      }); 

       xhr.open('POST', '../upload'); 
       xhr.send(data); 


      } 
     }; 
Các vấn đề liên quan