如何使用Spring REST多部分在块中发送大文件(REST客户端)

时间:2017-10-04 05:12:14

标签: java spring rest spring-mvc

我正在使用Spring REST编写一个客户端,它将文件上传到DB。 以下是我无法更改的服务器端控制器代码:

select
  case when count(1) > 0 then 'true' else 'false' end
from
  subject_table
where
  subject_id IN ('abc123', 'bcd3432', 'bla232')

我发送文件的客户端代码是:

@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);
}

但是当我使用这段代码发送让我们说50 MB的文件时,它会抛出&#34; 413请求实体太大的错误&#34;

有人可以帮我解决如何以块的形式发送大文件吗?

谢谢&amp;问候, Vikas Gite

2 个答案:

答案 0 :(得分:1)

You can specify a size of the upload file by using

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;
}

答案 1 :(得分:0)

<强>更新

好的,所以你设置了multipartMaxFileSize,但是如果你有一个大于10MB的文件,你还需要设置最大请求大小

似乎你在使用Spring 4.x

所以配置就像

spring.http.multipart.maxFileSize
spring.http.multipart.maxRequestSize

Official Source

<强> Depricated: 默认情况下,SimpleClientHttpRequestFactory在内部缓冲请求体。

将其设为假

SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setBufferRequestBody(false);

Source