How to send Multipart form data with restTemplate Spring-mvc

后端 未结 3 1018
时光说笑
时光说笑 2020-12-14 16:22

I am trying to upload a file with RestTemplate to Raspberry Pi with Jetty. On Pi there is a servlet running:



        
3条回答
  •  轮回少年
    2020-12-14 17:07

    Reading the whole file in a ByteArrayResource can be a memory consumption issue with large files.

    You can proxy a file upload in a spring mvc controller using a InputStreamResource:

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResponseEntity uploadImages(@RequestPart("images") final MultipartFile[] files) throws IOException {
        LinkedMultiValueMap map = new LinkedMultiValueMap<>();
        String response;
        HttpStatus httpStatus = HttpStatus.CREATED;
    
        try {
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    map.add("images", new MultipartInputStreamFileResource(file.getInputStream(), file.getOriginalFilename()));
                }
            }
    
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    
            String url = "http://example.com/upload";
    
            HttpEntity> requestEntity = new HttpEntity<>(map, headers);
            response = restTemplate.postForObject(url, requestEntity, String.class);
    
        } catch (HttpStatusCodeException e) {
            httpStatus = HttpStatus.valueOf(e.getStatusCode().value());
            response = e.getResponseBodyAsString();
        } catch (Exception e) {
            httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
            response = e.getMessage();
        }
    
        return new ResponseEntity<>(response, httpStatus);
    }
    
    class MultipartInputStreamFileResource extends InputStreamResource {
    
        private final String filename;
    
        MultipartInputStreamFileResource(InputStream inputStream, String filename) {
            super(inputStream);
            this.filename = filename;
        }
    
        @Override
        public String getFilename() {
            return this.filename;
        }
    
        @Override
        public long contentLength() throws IOException {
            return -1; // we do not want to generally read the whole stream into memory ...
        }
    }
    

提交回复
热议问题