programing

봄에 멀티파트와 @RequestBody를 함께 사용할 수 있습니까?

linuxpc 2023. 8. 19. 09:55
반응형

봄에 멀티파트와 @RequestBody를 함께 사용할 수 있습니까?

multipart file과 JSON 객체(@RequestBody)로 파라미터를 가질 수 있는 API를 만들고 싶습니다.이 API를 호출하는 동안 다음 스니펫을 찾으십시오.HTTP 415 지원되지 않는 미디어 유형 오류가 발생합니다.제거할 경우@RequestBody LabPatientInfo reportData그러면 잘 작동합니다.

@RequestMapping(value={"/lab/saveReport"}, method={RequestMethod.POST}, 
                consumes={"multipart/form-data"}, headers={"Accept=application/json"})
@ResponseBody
public ResponseEntity<String>
saveReport(@RequestParam(value="reportFile") MultipartFile reportFile,
           @RequestBody LabPatientInfo reportData) throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json; charset=utf-8");
    logger.info("in Lab Save Report");
    logger.info("Report Data {} ", reportData);
    //logger.info("Request BODY {} ", request.getAttribute("data"));
    return new ResponseEntity<String>(HttpStatus.OK);
}

다음은 LabPatientInfo 클래스입니다.

@RooJson(deepSerialize = true)
@RooToString
public class LabPatientInfo {
    
    private String firstName;
    private String phoneNumber;
    private String DateOfBirth;
    private Integer age;
    private String gender;
    private String refferedBy; 
    private String reportfile;
    private String reportType;
    private String reportDate;
    private String purpose;
    private String followUpDate;
    private List<ReportDataInfo> analytes;

API를 치는 동안 업로드된 파일로 JSON 객체를 따라가고 있습니다.

{
    "firstName":"abc",
    "phoneNumber":"898989",
    "DateOfBirth":"asas",
    "age":"asas",
    "gender":"asas",
    "refferedBy":"asas",
    "reportfile":"asas",
    "reportType":"asas",
    "reportDate":"asas",
    "purpose":"asas",
    "followUpDate":"asas",
    "analytes":null
}

사용할 수 있습니다.@RequestPart아래와 같이이것은 json 객체와 멀티파트 파일을 모두 지원합니다.

@ResponseBody
public ResponseEntity<String>
saveReport(@RequestPart (value="reportFile") MultipartFile reportFile,
           @RequestPart LabPatientInfo reportData) throws IOException {

curl을 사용하여 테스트하기 위해 json 부품(reportData)에 대한 파일을 하나 생성할 수 있습니다.예를 들어, "mydata.json" 파일을 만들고 그 파일에 json 페이로드를 붙여넣는다고 가정합니다.그리고 reportFile이 "report.txt"라고 말합니다.이제 아래와 같이 컬을 사용하여 요청을 보낼 수 있습니다.

curl -v -H "Content-Type:multipart/form-data" -F "reportData=@mydata.json;type=application/json" -F "reportFile=@report.txt;type=text/plain"  http://localhost:8080/MyApp/lab/saveReport

json 개체와 일반 파일을 수신하는 게시 방법의 예:

public ResponseEntity<Resource> postGenerateReport(@RequestPart GenerateReportDTO, generateReportDTO, @RequestPart MultipartFile jxhtmlReport)

PostMan 설정(또는 컬 또는 기타 REST 테스트 유틸리티)의 경우 다음 두 가지 요소가 포함된 폼 데이터 요청을 추가하면 됩니다.

  1. Key:generateReportDTO,Value:확장자가 .json인 파일(및 개체와 호환되는 컨텐츠)
  2. Key:jxhtmlReport,Value:그냥 아무 파일이나.

매개 변수가 @RequestPart로 주석을 달면 요청 파트의 'Content-Type'을 염두에 두고 메서드 인수를 해결하기 위해 파트의 내용이 HttpMessageConverter를 통해 전달됩니다.이는 @RequestBody가 일반 요청의 내용을 기반으로 인수를 해결하기 위해 수행하는 작업과 유사합니다.

따라서 @Requestbody를 "abaghel"로 @RequestPart로 구문 분석하고 reportData는 json 파일이어야 합니다.

Spring Roo 2.0.0.M3는 REST API의 자동 비계 지원을 포함합니다.

자세한 내용은 참조 매뉴얼의 REST API를 참조하십시오.

M3 버전은 최신 버전에서 변경될 수 있는 아티팩트를 생성하므로 RC1 이상으로 열어도 프로젝트가 자동으로 업그레이드되지 않을 수 있습니다.

포스가 당신과 함께 하길.

언급URL : https://stackoverflow.com/questions/40924649/can-we-use-multipart-and-requestbody-together-in-spring

반응형