2015-12-14 48 views
1

我正在研究一项服务(前端和后端),将允许上传多个文件和元数据到每个文件,所以我会能够生成保存文件的特定路径。 (元数据会给我所有关于路径的信息)。另外,该请求将包含需要保存到数据库的信息(这部分工作正常),因此它的所有事务都是如此。所以我唯一不知道的是如何发送和接受每个文件的元数据。多元文件上传与元数据相关的每个文件在一个单一的http请求

前端:Angularjs

后端:Groovy的/爪哇,春季3.0

@RequestMapping(value = "/view/single/multi-file", method = POST, produces = APPLICATION_JSON_VALUE) 
def createNewAdjustment(@RequestParam("files") List<List<MultipartFile>> files, 
         @RequestParam("data") List<DataRequest> data){} 
在上面的代码

所以:

- the list of lists: are the files that needs to be processed and saved. 
- the data: is the list of objects that needs to be processed,saved and interconnect them with files. 

该请求有效载荷看起来像这样:

------WebKitFormBoundaryPve8x58T1pAIsQOS 
Content-Disposition: form-data; name="data" 

{"rollNumber":"1111111111111","compId":213131,"adjId":"260b018c-5921-4c1c-aa99-ba8587ee4777"} 
------WebKitFormBoundaryPve8x58T1pAIsQOS 
Content-Disposition: form-data; name="files"; filename="some.json.gz" 
Content-Type: application/x-gzip 


------WebKitFormBoundaryPve8x58T1pAIsQOS 
Content-Disposition: form-data; name="files"; filename="someother.csv.gz" 
Content-Type: application/x-gzip 


------WebKitFormBoundaryPve8x58T1pAIsQOS-- 

Yo你可以看到'名称:'文件''重复2次,我不确定如何手动设置或/和附加更多的请求。有任何想法吗 ?

回答

0

我找到了解决这个:)

从前端

所以(AngularJS):

$upload.upload({ 
    url : 'upload', 
    headers: {'myHeaderKey': 'myHeaderVal'}, 
    data : { 
     myModel : $scope.myModel, 
     array: [1,2,3] 
    }, 
    formDataAppender: function(fd, key, val) { 
     if (angular.isArray(val)) { 
      angular.forEach(val, function(v) { 
       fd.append(key, v); 
      }); 
     } else { 
      fd.append(key, val); 
     } 
    }, 
    file : $file, 
    fileFormDataName: 'myFile' 
}) 

formDataAppender将新部件添加到该请求,并可以为每一个自定义名称你正在发送的单个文件。 (正是需要的)。

从后端(春季Groovy中):

@Autowired DbRepository dbRepo 
@RequestMapping(value = "/docs/upload", method = POST) 
ResponseEntity<String> docsUpload(HttpServletRequest request, @RequestParam("data") String data) throws IOException { 
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request 
    List<List<MultipartFile>> files = new ArrayList<List<MultipartFile>>() 
    multipartRequest.getFileNames().each { 
     files.add(multipartRequest.getFiles(it)) 
    } 
    PoJoObject pojoObject = mapper.readValue(data, PoJoObject) 

    files.each { def it -> 
     it.each { def itf -> 
     log.debug(itf.originalFilename) // the name of the actual file 
     log.debug(itf.name) // the custimized field from formDataAdapter 

     // in here you can process every field in 'PoJoObject' and make 
     // relation to the the file 
     } 
    } 

    return null; 
} 

该解决方案对我的作品和我解决了:)现在我可以保存数据和相应的文件事务在一个请求的问题。

相关问题