Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring upload non multipart file as a stream

I am working with Spring Boot 1.2.5 and I would like to upload a raw binary file to a controller. The file size may be large so I do not want to hold the whole request in memory but instead stream the file, in fact the file is being generated as transmission start so the client doesn't even know the size of the file. I see an example of how to do something similar with a multipart encoded file upload here. However, I do not want a multipart encoded upload, just a raw stream of bytes. I can't seem to find a way to handle this use-case in spring.

like image 713
cmaynard Avatar asked Sep 28 '16 13:09

cmaynard


1 Answers

You can just consume the HttpServletRequest inputstream.
Just be aware that if you have any filters that pre process the request and consume the inputstream then this might not work.

@ResponseBody
@RequestMapping(path="fileupload", method = RequestMethod.POST, consumes = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void fileUpload(HttpServletRequest request) throws IOException {
    Files.copy(request.getInputStream(), Paths.get("myfilename"));
}
like image 168
Magnus Avatar answered Jan 01 '23 21:01

Magnus