1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.