Home » Java » Send Byte array as file in using http client in java

Send Byte array as file in using http client in java

Posted by: admin December 28, 2021 Leave a comment

Questions:

We have byte array of file and we want to upload it as file.
FileBody only gets File as parameter but we have a array of bytes.

One solution is to save byte array into file and then send it
but it is not appropriate for me.

byte b[]= new byte[1000];
//fill b
MultipartEntity form = new MultipartEntity();
form.addPart("file", new FileBody(/* b? */));

thanks.

Answers:

You can do something like

HttpClient client=null;
byte b[]= new byte[1000];
MultipartEntity form = new MultipartEntity();
ContentBody cd = new InputStreamBody(new ByteArrayInputStream(b), "my-file.txt");
form.addPart("file", cd);

HttpEntityEnclosingRequestBase post = new HttpPost("");//If a PUT request then `new HttpPut("");`
post.setEntity(form);
client.execute(post);

###

You can use ByteArrayBody instead InputStreamBody or FileBody.

HttpClient client=null;
byte b[]= new byte[1000];
MultipartEntity form = new MultipartEntity();
ContentBody cd = new ByteArrayBody(b, "my-file.txt");
form.addPart("file", cd);

HttpEntityEnclosingRequestBase post = new HttpPost("");
post.setEntity(form);
client.execute(post);