Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send Byte array as file in using http client in java

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.

like image 968
Hossein Nasr Avatar asked Mar 14 '13 10:03

Hossein Nasr


2 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);
like image 193
Arun P Johny Avatar answered Sep 22 '22 00:09

Arun P Johny


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);
like image 20
Frédéric Chopin Avatar answered Sep 21 '22 00:09

Frédéric Chopin