多文件上载,包含与单个http请求中的每个文件相关的元数据

时间:2015-12-14 19:50:05

标签: angularjs spring http file-upload groovy

我正在处理一项服务(前端和后端),它允许将多个文件和元数据上传到每个文件,因此我将能够生成保存文件的特定路径。 (元数据将为我提供有关路径的所有信息)。此外,请求将包含需要保存到DB的信息(此部分工作正常),因此它的所有事务性。因此,我唯一能解决的问题是如何向每个文件发送和接受元数据。

前端:Angularjs

后端:Groovy / Java,Spring 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--

您可以看到&#39;名称:&#34;文件&#34;&#39; 重复2次,我不确定如何手动设置或/和将更多内容附加到请求中。有什么想法吗?

1 个答案:

答案 0 :(得分: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将为请求添加新部件,您可以为要发送的每个文件自定义名称。 (确切地说是需要的)。

从后端(Spring 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;
}

此解决方案适用于我并解决了我的问题:)现在我可以在一个请求中以事务方式保存数据和相应的文件。