6

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.

2 Answers 2

11

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);
Sign up to request clarification or add additional context in comments.

2 Comments

which is the version used? I've used 4.0.1
Any way, he can use a InputStreamBody based on the syntax of the version used
6

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);

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.