JSON을 사용한 Spring MVC 멀티 파트 요청
Spring MVC를 사용하여 JSON 데이터가 포함 된 파일을 게시하고 싶습니다. 그래서 휴식 서비스를 개발했습니다.
@RequestMapping(value = "/servicegenerator/wsdl", method = RequestMethod.POST,consumes = { "multipart/mixed", "multipart/form-data" })
@ResponseBody
public String generateWSDLService(@RequestPart("meta-data") WSDLInfo wsdlInfo,@RequestPart("file") MultipartFile file) throws WSDLException, IOException,
JAXBException, ParserConfigurationException, SAXException, TransformerException {
return handleWSDL(wsdlInfo,file);
}
나머지 클라이언트에서를 사용하여 요청을 보내면 content-Type = multipart/form-data or multipart/mixed다음 예외가 발생합니다.org.springframework.web.multipart.support.MissingServletRequestPartException
누구든지이 문제를 해결하는 데 도움을 줄 수 있습니까?
@RequestPartMultipart와 JSON을 모두 서버에 보낼 수 있습니까 ?
이것이 JSON 데이터로 Spring MVC Multipart Request를 구현 한 방법입니다.
JSON 데이터가 포함 된 멀티 파트 요청 (혼합 멀티 파트라고도 함) :
Spring 4.0.2 Release의 RESTful 서비스를 기반으로 첫 번째 부분은 XML 또는 JSON 형식의 데이터로, 두 번째 부분은 파일로 HTTP 요청은 @RequestPart로 수행 할 수 있습니다. 다음은 샘플 구현입니다.
자바 스 니펫 :
Controller의 Rest 서비스에는 이러한 Multipart + JSON 요청을 처리하기 위해 @RequestPart 및 MultipartFile이 혼합되어 있습니다.
@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
consumes = {"multipart/form-data"})
@ResponseBody
public boolean executeSampleService(
@RequestPart("properties") @Valid ConnectionProperties properties,
@RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
return projectService.executeSampleService(properties, file);
}
프런트 엔드 (자바 스크립트) 스 니펫 :
FormData 개체를 만듭니다.
아래 단계 중 하나를 사용하여 FormData 개체에 파일을 추가합니다.
- 파일이 "file"유형의 입력 요소를 사용하여 업로드 된 경우 FormData 객체에 추가합니다.
formData.append("file", document.forms[formName].file.files[0]); - 파일을 FormData 개체에 직접 추가합니다.
formData.append("file", myFile, "myfile.txt");또는formData.append("file", myBob, "myfile.txt");
- 파일이 "file"유형의 입력 요소를 사용하여 업로드 된 경우 FormData 객체에 추가합니다.
문자열 화 된 JSON 데이터로 Blob을 만들고 FormData 개체에 추가합니다. 이로 인해 다중 파트 요청에서 두 번째 파트의 컨텐츠 유형이 파일 유형 대신 "application / json"이됩니다.
서버에 요청을 보냅니다.
요청 세부 정보 :
Content-Type: undefined. 이로 인해 브라우저는 Content-Type을 multipart / form-data로 설정하고 경계를 올바르게 채 웁니다. Content-Type을 multipart / form-data로 수동 설정하면 요청의 경계 매개 변수를 채우지 못합니다.
자바 스크립트 코드 :
formData = new FormData();
formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
"name": "root",
"password": "root"
})], {
type: "application/json"
}));
요청 세부 정보 :
method: "POST",
headers: {
"Content-Type": undefined
},
data: formData
페이로드 요청 :
Accept:application/json, text/plain, */*
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryEBoJzS3HQ4PgE1QB
------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="file"; filename="myfile.txt"
Content-Type: application/txt
------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="properties"; filename="blob"
Content-Type: application/json
------WebKitFormBoundaryvijcWI2ZrZQ8xEBN--
작동해야합니다!
client (angular):
$scope.saveForm = function () {
var formData = new FormData();
var file = $scope.myFile;
var json = $scope.myJson;
formData.append("file", file);
formData.append("ad",JSON.stringify(json));//important: convert to JSON!
var req = {
url: '/upload',
method: 'POST',
headers: {'Content-Type': undefined},
data: formData,
transformRequest: function (data, headersGetterFunction) {
return data;
}
};
Backend-Spring Boot:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody
Advertisement storeAd(@RequestPart("ad") String adString, @RequestPart("file") MultipartFile file) throws IOException {
Advertisement jsonAd = new ObjectMapper().readValue(adString, Advertisement.class);
//do whatever you want with your file and jsonAd
As documentation says:
Raised when the part of a "multipart/form-data" request identified by its name cannot be found.
This may be because the request is not a multipart/form-data either because the part is not present in the request, or because the web application is not configured correctly for processing multipart requests -- e.g. no MultipartResolver.
참고URL : https://stackoverflow.com/questions/21329426/spring-mvc-multipart-request-with-json
'IT TIP' 카테고리의 다른 글
| 현재 파일을 덮어 쓰도록 SVN 체크 아웃 명령 강제 실행 (0) | 2020.11.23 |
|---|---|
| MS Excel 데이터를 SQL Server에 붙여 넣기 (0) | 2020.11.23 |
| 공통된 참조가없고 지정된 것도 없습니다. (0) | 2020.11.22 |
| 모든 axios 요청에 대한 Authorization 헤더 첨부 (0) | 2020.11.22 |
| MySQL AUTO_INCREMENT가 롤백되지 않습니다. (0) | 2020.11.22 |