Repository navigation
Closed
Labels
in: webIssues in web modules (web, webmvc, webflux, websocket)type: enhancementA general enhancement
Milestone
Description
Greg Adams opened SPR-13571 and commented
I've been trying to send a multipart post via restTemplate and have been unable to get it to work with anything but FileSystemResource. In my use case (a weird file-forwarding use case) this forces me to copy a MultiPartFile InputStream into a temp file in order be able to create a FileSystemResource, which seems undesirable.
Here's a testing version of the file-receiving controller (from another project, running in another servlet container):
@RestController
public class FileReceiveController {
private Log log = LogFactory.getLog(FileReceiveController.class);
@RequestMapping(method = RequestMethod.POST)
public void uploadFile(@RequestParam("customerId") int customerId, @RequestPart("file") MultipartFile multipartFile) {
log.info("customerId: " + customerId);
log.info("Received multipart file - original filename: " + multipartFile.getOriginalFilename());
log.info("content-type: " + multipartFile.getContentType());
log.info("size: " + multipartFile.getSize());
}
}
Here's the file-forwarding controller:
@RestController
public class FileForwardController {
private RestTemplate restTemplate;
public FileForwardController() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setBufferRequestBody(false);
this.restTemplate = new RestTemplate(requestFactory);
}
@RequestMapping(method = RequestMethod.POST)
public void uploadFile(@RequestParam("customerId") int customerId, @RequestPart("file") MultipartFile multipartFile) {
MultiValueMap<String,Object> parts = new LinkedMultiValueMap<>();
parts.add("customerId", customerId);
try {
// copy to temp file and use FileSystemResource
// File tempFile = File.createTempFile("xyz", "");
// FileCopyUtils.copy(multipartFile.getInputStream(), new FileOutputStream(tempFile));
// parts.add("file", new FileSystemResource(tempFile));
// OR use InputStreamResource (broken)
parts.add("file", new InputStreamResource(multipartFile.getInputStream()));
// OR use ByteArrayResource (broken)
// parts.add("file", new ByteArrayResource(multipartFile.getBytes()));
} catch (IOException e) {
throw new RuntimeException(e);
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String,Object>> request = new HttpEntity<>(parts, headers);
restTemplate.exchange("http://localhost:8080", HttpMethod.POST, request, Void.class);
}
}
In this form, the restTemplate.exchange call throws
org.springframework.web.client.HttpClientErrorException: 400 Bad Request
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:614)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:570)
The ByteArrayResource form does the same thing. Only the FileSystemResource form works.
Affects: 4.1.7
Issue Links:
- Read large data using InputStreamResource at ResourceHttpMessageConverter [SPR-13443] #18023 Read large data using InputStreamResource at ResourceHttpMessageConverter
- RestTemplate with InputStreamResource does not work if Content-Length is not set [SPR-12017] #16633 RestTemplate with InputStreamResource does not work if Content-Length is not set
- HTTP Response should not contain both Transfer-Encoding and Content-Length headers [SPR-15212] #19776 HTTP Response should not contain both Transfer-Encoding and Content-Length headers
- Update advice on contentLength() in subclasses of InputStreamResource #20990 Consistent treatment of InputStreamResource subclasses
- Support use of MultipartFile as input to RestTemplate or WebClient [SPR-16808] #21348 Support use of MultipartFile as input to RestTemplate or WebClient
Referenced from: commits 27c1280
0 votes, 6 watchers
Metadata
Metadata
Assignees
Labels
in: webIssues in web modules (web, webmvc, webflux, websocket)type: enhancementA general enhancement
Activity
spring-projects-issues commentedon Dec 28, 2015
Brian Clozel commented
In order to properly write the multipart request, the
FormHttpMessageConverterconfigured automatically with theRestTemplatewill write all parts; if a part inherits from Resource, it calls theResource.getFilename()method to get a file name, see the getFilename() method. If no file name is found, then this part is written as a "regular" part, not a file, in the content-disposition part of the message.In your case, you could do the following:
There are a few ways to improve this situation in the framework.
Resource; the problem is, we don't have that information and we can only try to guess. This can also lead to new issues, since we'd be considering parts as file whereas those weren't in the pastMultipartFileResourceimplementation and add it in the reference documentationCould you try the workaround I told you about and confirm this works?
Let me know what you think about the solutions listed here.
Thanks!
spring-projects-issues commentedon Dec 29, 2015
Greg Adams commented
I've tried with code nearly identical to your comment
the restTemplate.exchange call throws the following exception:
spring-projects-issues commentedon Dec 29, 2015
Greg Adams commented
It looks like the InputStreamResource.getInputStream() method is called twice, once from MultipartFileResource.contentLength() (via ResourceHttpMessageConverter.getContentLength(Resource, MediaType)) and again from ResourceHttpMessageConverter.writeInternal(Resource, HttpOutputMessage), and InputStreamResource doesn't allow multiple calls to getInputStream.
spring-projects-issues commentedon Dec 29, 2015
Greg Adams commented
Using something like this works:
I'm still not sure it's a good idea to call multipartFile.getBytes() like this. Doesn't that read the entire file into heap? Wouldn't that expose you to the possibility of OOM for very large files?
spring-projects-issues commentedon Jan 13, 2016
Marcus Schulte commented
Actually
ResourceHttpMessageConverterseems a bit broken to me, when it checks whether it should ask a resource for its content-length by comparing its type to a constant:This gives anyone inheriting from
InputStreamResourcea hard time conforming to the Liskov principle.For me, a combination of a custom-named resource and a slightly altered version of
ResourceHttpMessageConverterdoes the trick:Then, a resource like the following works
Of course, the broken Converter needs to be replaced in the RestTemplate:
A method like
Resource.isContentLengthAvailable()along with corresponding code to support it would be nice to have ...spring-projects-issues commentedon Feb 11, 2016
Juergen Hoeller commented
At this point, a dedicated
isContentLengthAvailable()method doesn't seem to be worth it. After all, this is primarily a limitation ofInputStreamResourceitself which unfortunately - for backwards compatibility reasons - needs to supportcontentLength()calls that just need to determine the body length, never actually reading the body with the same resource afterwards.So effectively, all that our check there does is to bypass a standard implementation that is known to be broken for that particular purpose: If we receive a plain
InputStreamResource, we know we can't determine the content length if we intend to read the body as well. For any custom subclass ofInputStreamResource, we optimistically expect it to provide a proper content length... since we do not reliably know that it is broken for the given use case, we'd rather not expect so upfront. Such a subclass should be able to override thecontentLength()implementation without having to switch any extra flag to make it work.That said, for any custom subclass of
InputStreamResource, there should be a way to bypass content length determination the same way at least. Your suggestion of lettingResourceHttpMessageConvertercheck for negative content length values and bypass content length handling the same way sounds good there; I've rolled this into 4.3.Juergen