4

I am trying to POST a file using HttpClient. However, I don't have access to the actual File but I have access to its InputStream. Is there a way I can still POST the file?

This is what I have done so far:

 public void sendFile (InputStream instream) {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod("http://localhost:8080/myservice/testupload");
    Part[] parts = new Part[] {
            //new FilePart("myFile", file.getName(), file)
    };
    method.setRequestEntity(
    new MultipartRequestEntity(parts, method.getParams()));
    client.executeMethod(method);
 }

as you can see, the FilePart needs file but I have InputStream. How can I POST the input stream as a file?

birdy
  • 9,286
  • 24
  • 107
  • 171

1 Answers1

2

Looking at the javadoc for FilePart, there is a constructor which accepts PartSource instead of File, and there is a subclass of PartSource called ByteArrayPartSource, which you can construct from byte[]; you can obtain this from the InputStream as described here.

Community
  • 1
  • 1
Andy Turner
  • 137,514
  • 11
  • 162
  • 243