복붙노트

[SPRING] 다중 파일 업로드 봄 부팅

SPRING

다중 파일 업로드 봄 부팅

나는 봄 부팅을 사용하고 멀티 파트 파일 업로드를 받기 위해 컨트롤러를 사용하고자한다. 파일을 보낼 때 오류 415 지원되지 않는 콘텐츠 형식 응답을 계속 및 컨트롤러 도달했습니다.

There was an unexpected error (type=Unsupported Media Type, status=415).
Content type 'multipart/form-data;boundary=----WebKitFormBoundary1KvzQ1rt2V1BBbb8' not supported

Ive는 html / jsp 페이지에서 form : action을 사용하여 보내고 RestTemplate을 사용하는 독립 실행 형 클라이언트 응용 프로그램에서도 전송을 시도했습니다. 모든 시도는 같은 결과를 준다.

multipart / form-data; 경계 = XXXXX는 지원되지 않습니다.

다중 매개 변수 문서에서는 경계 매개 변수가 다중 부분 업로드에 추가되어야하지만 이는 "multipart / form-data"를받는 컨트롤러와 일치하지 않는 것처럼 보입니다.

내 컨트롤러 방법은 다음과 같이 설정됩니다.

@RequestMapping(value = "/things", method = RequestMethod.POST, consumes = "multipart/form-data" ,
                                     produces = { "application/json", "application/xml" })
     public ResponseEntity<ThingRepresentation> submitThing(HttpServletRequest request,
                                     @PathVariable("domain") String domainParam,
                                     @RequestParam(value = "type") String thingTypeParam,
                                     @RequestBody MultipartFile[] submissions) throws Exception

빈 설정 사용

 @Bean
 public MultipartConfigElement multipartConfigElement() {
     return new MultipartConfigElement("");
 }

 @Bean
 public MultipartResolver multipartResolver() {
     org.springframework.web.multipart.commons.CommonsMultipartResolver multipartResolver = new org.springframework.web.multipart.commons.CommonsMultipartResolver();
     multipartResolver.setMaxUploadSize(1000000);
     return multipartResolver;
 }

당신이 볼 수 있듯이, 소비 유형을 "multipart / form-data"로 설정했지만 multipart가 전송되면 경계 매개 변수가 있어야하며 임의의 경계 문자열을 배치해야합니다.

아무도 내 컨트롤러 설정과 일치하도록 컨트롤러에서 컨텐츠 유형을 일치 시키거나 내 요청을 변경하는 방법을 알려주십시오.

내 보내려는 시도 ... 1 시도 ...

<html lang="en">
<body>

    <br>
    <h2>Upload New File to this Bucket</h2>
    <form action="http://localhost:8280/appname/domains/abc/things?type=abcdef00-1111-4b38-8026-315b13dc8706" method="post" enctype="multipart/form-data">
        <table width="60%" border="1" cellspacing="0">
            <tr>
                <td width="35%"><strong>File to upload</strong></td>
                <td width="65%"><input type="file" name="file" /></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="submit" name="submit" value="Add" /></td>
            </tr>
        </table>
    </form>
</body>
</html>

시도 2 ....

RestTemplate template = new RestTemplate();
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("file", new FileSystemResource(pathToFile));

try{

    URI response = template.postForLocation(url, parts);
}catch(HttpClientErrorException e){
    System.out.println(e.getResponseBodyAsString());
}

시도 3 ...

FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
        formHttpMessageConverter.setCharset(Charset.forName("UTF8"));


        RestTemplate restTemplate = new RestTemplate();

        restTemplate.getMessageConverters().add( formHttpMessageConverter );
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
        map.add("file", new FileSystemResource(path));

        HttpHeaders imageHeaders = new HttpHeaders();
        imageHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);

        HttpEntity<MultiValueMap<String, Object>> imageEntity = new HttpEntity<MultiValueMap<String, Object>>(map, imageHeaders);
        ResponseEntity e=  restTemplate.exchange(uri, HttpMethod.POST, imageEntity, Boolean.class);
        System.out.println(e.toString());

해결법

  1. ==============================

    1.

    @RequestBody MultipartFile[] submissions
    

    해야한다

    @RequestParam("file") MultipartFile[] submissions
    

    파일은 요청 본문이 아니며 요청의 일부이며 요청을 MultiPartFile 배열로 변환 할 수있는 기본 제공 HttpMessageConverter가 없습니다.

    또한 HttpServletRequest를 MultipartHttpServletRequest로 바꿀 수 있습니다. MultipartHttpServletRequest를 사용하면 개별 파트의 헤더에 액세스 할 수 있습니다.

  2. ==============================

    2.다음과 같은 컨트롤러 메소드를 사용하면됩니다.

    다음과 같은 컨트롤러 메소드를 사용하면됩니다.

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<?> uploadFile(
        @RequestParam("file") MultipartFile file) {
    
      try {
        // Handle the received file here
        // ...
      }
      catch (Exception e) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
      }
    
      return new ResponseEntity<>(HttpStatus.OK);
    } // method uploadFile
    

    Spring Boot에 대한 추가 구성없이.

    다음 html 양식 클라이언트 측 사용 :

    <html>
    <body>
      <form action="/uploadFile" method="POST" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="Upload"> 
      </form>
    </body>
    </html>
    

    파일 크기에 대한 제한을 설정하려면 application.properties에서 수행 할 수 있습니다.

    # File size limit
    multipart.maxFileSize = 3Mb
    
    # Total request size for a multipart/form-data
    multipart.maxRequestSize = 20Mb
    

    또한 Ajax 파일을 보내려면 여기를 살펴보십시오. http://blog.netgloo.com/2015/02/08/spring-boot-file-upload-with-ajax/

  3. ==============================

    3.최신 버전의 SpringBoot는 여러 파일을 매우 쉽게 업로드합니다. 브라우저 측면에서 표준 HTML 업로드 양식이 필요하지만 여러 입력 요소 (업로드 할 파일 당 하나, 매우 중요 함), 모두 동일한 요소 이름 (아래 예제에서는 name = "files")을 가지고 있습니다.

    최신 버전의 SpringBoot는 여러 파일을 매우 쉽게 업로드합니다. 브라우저 측면에서 표준 HTML 업로드 양식이 필요하지만 여러 입력 요소 (업로드 할 파일 당 하나, 매우 중요 함), 모두 동일한 요소 이름 (아래 예제에서는 name = "files")을 가지고 있습니다.

    그런 다음 서버의 Spring @Controller 클래스에서 필요한 것은 다음과 같습니다.

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
        public @ResponseBody ResponseEntity<?> upload(
            @RequestParam("files") MultipartFile[] uploadFiles) throws Exception     
    {
        ...now loop over all uploadFiles in the array and do what you want
      return new ResponseEntity<>(HttpStatus.OK);
    }
    

    그것들은 까다로운 부분입니다. 즉, 각각 "파일"이라는 이름의 다중 입력 요소를 작성하고 MultipartFile [] (배열)을 요청 매개 변수로 사용한다는 것을 아는 것이 까다로운 사항이지만 간단합니다. MultipartFile 항목을 처리하는 방법에 대해서는 알지 못합니다. 이미 많은 문서가 있기 때문입니다.

  4. ==============================

    4.

       @Bean
        MultipartConfigElement multipartConfigElement() {
            MultipartConfigFactory factory = new MultipartConfigFactory();
            factory.setMaxFileSize("5120MB");
            factory.setMaxRequestSize("5120MB");
            return factory.createMultipartConfig();
        }
    

    콩을 정의하는 클래스에 넣으십시오.

  5. ==============================

    5.

    @RequestMapping(value="/add/image", method=RequestMethod.POST)
    public ResponseEntity upload(@RequestParam("id") Long id, HttpServletResponse response, HttpServletRequest request)
    {   
        try {
            MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)request;
            Iterator<String> it=multipartRequest.getFileNames();
            MultipartFile multipart=multipartRequest.getFile(it.next());
            String fileName=id+".png";
            String imageName = fileName;
    
            byte[] bytes=multipart.getBytes();
            BufferedOutputStream stream= new BufferedOutputStream(new FileOutputStream("src/main/resources/static/image/book/"+fileName));;
    
            stream.write(bytes);
            stream.close();
            return new ResponseEntity("upload success", HttpStatus.OK);
    
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity("Upload fialed", HttpStatus.BAD_REQUEST);
        }   
    }
    
  6. ==============================

    6.컨트롤러에서, 당신의 방법은;

    컨트롤러에서, 당신의 방법은;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
        public ResponseEntity<SaveResponse> uploadAttachment(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
    ....
    

    또한 최대 파일 크기와 요청 크기를 지원하려면 application.yml (또는 application.properties)을 업데이트해야합니다.

    spring:
        http:
            multipart:
                max-file-size: 5MB
                max-request-size: 20MB
    
  7. from https://stackoverflow.com/questions/25699727/multipart-file-upload-spring-boot by cc-by-sa and MIT license