2016-11-22 58 views
0

我上傳一個excel文件在前端(angularjs),並希望在後端(grails資源文件)接收它。我不應該在我的項目中使用GSP.So如何接收通過angularjs發送的文件?如何從grails(後端)中的angularjs接收上傳的文件?

AngularJs代碼,

$scope.uploadExcelFile =function (file) { 
     var doc = file 
     var filesArr = []; 
     if (doc) { 
      filesArr.push({file: doc}); 
      uploadCurry(filesArr); 
     } 
    } 
    function uploadCurry(queue){ 
     if (arguments.length) { 
      this.q = queue 
     } 
     if (this.q.length) { 
      var curr = this.q.pop(); 
      upload(curr.file); 
     } 
    } 
    function upload(file) { 
     if (file) { 
      var postdata = { 
       file: file, 
      } 
      roleProfileService.importExcleFile(postdata).then(function(res) { 
       console.log(res); 
      }) 
     } 
    } 

角服務文件,

var importExcleFile = function(file,callback){ 

     return $upload.upload({ 
      url: '/api/importFile/profile', 
      method: 'POST', 
      file: file 
     }).progress(function(evt) { 
      _log('progress: ' + parseInt(100.0 * evt.loaded/evt.total) + '% file :'+ evt.config.file.name); 
      roleProfileService.progress = 'Loading '+ evt.config.file.name +" : "+ parseInt(100.0 * evt.loaded/evt.total)+"%" 
     }).success(function(data, status, headers, config) { 
      _log('file ' + config.file.name + 'is uploaded successfully. Response: ' + data); 
      roleProfileService.uploadsuccess = true; 
      if(callback) callback(); 


     }).error(function(a,b,c,d,e){ 
      _log("err", a,b,c,d,e); 
      roleProfileService.uploadfail = true; 
     }); 
    } 

Grails的資源文件,

@Path('/api/importFile') 
@Consumes(['application/json','text/plain','application/vnd.ms-excel']) 
@Produces(['application/json']) 

class KsaResource { 
    KsaService ksaService 

    @GET 
    @Path('profile') 
    Response getAllKsaData(MultipartFile file) { 
     //how to receive uploaded file here? 
     List<Job> jobSavedList = ksaService.importExcelData(file); 
     //rest of code 
    } 
} 

回答

0

我們可以寫一個控制器接收文件

class ImportRoleProfileController { 

    SpringSecurityService springSecurityService; 

    def importUpload() { 
     User currentUser = springSecurityService.getCurrentUser(); 
     def file = request.getFile('file') 
     Workbook workbook = Workbook.getWorkbook(file.getInputStream()); 
     int sheet_Num = workbook.getNumberOfSheets(); 
相關問題