Reputation: 3912
In my custom application I accept files through a file upload form and get MultipartFile object. Then according to the other parameters in the upload form I make some processing and I prepare another post request including the file and send the request to another server.
The code I use is as follows :
In the controller part I take the input steram
MultipartFile file = uploadedFile.getFile();
InputStream inputStream = file.getInputStream();
The stream is passed to service method and the new request is prepared as below
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost(url + port + path);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
.... other parameters set here....
multipartEntityBuilder.addBinaryBody("attachment", IOUtils.toByteArray(inputStream), ContentType.APPLICATION_OCTET_STREAM, fileName);
HttpEntity httpEntity = multipartEntityBuilder.build();
uploadFile.setEntity(httpEntity);
HttpResponse httpResponse = closeableHttpClient.execute(uploadFile);
Is there a more efficient way of doing this, is the transformation of
file.getInputStream()
to
byte[] // by IOUtils.toByteArray(inputStream)
really needed?
Any other advice for the method is also appreciated.
Upvotes: 1
Views: 667
Reputation: 3912
We can call the multipartEntityBuilder.addBinaryBody
method directly with inputStream
as below:
multipartEntityBuilder.addBinaryBody("attachment", IOUtils.toByteArray(inputStream), ContentType.APPLICATION_OCTET_STREAM, fileName);
So there will be a great increase in memory usage that was caused by IOUtils.toByteArray() method and file will be sent via streaming.
Upvotes: 1