2015-12-14 24 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; 
} 

該解決方案對我的作品和我解決了:)現在我可以保存數據和相應的文件事務在一個請求的問題。

相關問題