如何在块中使用Spring REST multipart发送大文件(REST客户端)
我使用spring REST编写了一个将文件上传到数据库的客户端。 以下是我无法更改的服务器端控制器代码:
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<UploadResponseDto> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
String contentType = file.getContentType();
if ( contentType == null || !contentType.equalsIgnoreCase(APPLICATION_OCTET_STREAM)) {
contentType = APPLICATION_OCTET_STREAM;
}
GridFSFile gridFSFile = gridFsTemplate.store(file.getInputStream(), file.getOriginalFilename(), contentType);
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
String fileLocation = linkTo(FileAttachmentController.class).slash(gridFSFile.getId()).toUri().toString();
headers.add(LOCATION, fileLocation);
UploadResponseDto uploadResponseDto = new UploadResponseDto(file.getOriginalFilename(), fileLocation);
return new ResponseEntity<>(uploadResponseDto, headers, HttpStatus.CREATED);
}
我的客户端发送文件的代码是:
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setBufferRequestBody(false);
RestTemplate restTemplate = new RestTemplate(factory);
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.AUTHORIZATION, "Bearer " + token);
headers.set("Accept", "application/json");
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
File file = new File(fileToUpload);
MultiValueMap<String, Object> data = new LinkedMultiValueMap<String, Object>();
ByteArrayResource resource = new ByteArrayResource(
Files.readAllBytes(Paths.get(fileToUpload))) {
@Override
public String getFilename() {
return file.getName();
}
};
data.add("file", resource);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(
data, headers);
ResponseEntity<Map> apiResponse = null;
apiResponse = restTemplate.exchange(
"http://{end_point_url}",
HttpMethod.POST, requestEntity, Map.class);
但是当我使用这段代码发送可以说50 MB文件时,它会抛出“413请求实体太大的错误”
有人可以帮我解决如何发送大块文件的问题吗?
感谢和问候,Vikas Gite
您可以使用指定上传文件的大小
org.springframework.web.multipart.commons.CommonsMultipartResolver
@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(54525952); //...specify your size of file (20971520 - 20 MB) (54525952 - 52 MB)
return multipartResolver;
}
更新
好吧,你已经设置了multipartMaxFileSize,但是如果你有一个大于10MB的文件,你还需要设置最大请求大小
似乎你正在使用Spring 4.x
所以配置就像
spring.http.multipart.maxFileSize
spring.http.multipart.maxRequestSize
官方来源
Depricated:默认情况下,SimpleClientHttpRequestFactory在内部缓冲请求主体。
把它弄错
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setBufferRequestBody(false);
资源
链接地址: http://www.djcxy.com/p/48741.html上一篇: How to send large file using Spring REST multipart in chunks (REST client)