views:

107

answers:

1

[edit] I've removed my convoluted and badly malformed question so that it doesn't detract from the very neat and correct answer beneath. Given the (surprising) difficulty of finding an on-line example for doing this incredibly common task, I hope Yoni gets a few more up-ticks for his response.

So... the question in a nutshell...

How do I use Apache.Commons to upload a file to some destination. I'm using it in Android and uploading to a PHP script, but obviously it can work from any Java program and to any HTTP based listener.

+1  A: 

From the api of MultipartRequestEntity:

File f = new File("/path/fileToUpload.txt");
PostMethod filePost = new PostMethod("http://host/some_path");
Part[] parts = {
    new StringPart("param_name", "value"),
    new FilePart(f.getName(), f)
};
filePost.setRequestEntity(
    new MultipartRequestEntity(parts, filePost.getParams())
);
HttpClient client = new HttpClient();
int status = client.executeMethod(filePost);
  • I don't think you need the content-disposition part, that is used for the other direction (when the browser downloads a file and needs to know what to do with it).
  • getParams.setParameter is optional. You can also set it directly on the HttpClient instance.
  • AFAIK, the order of setting request headers is irrelevant, as long as they are all set before you set the request body.
Yoni
someone needs to kiss you. you have no idea how painful it was trying to get this ridiculously "easy" answer. I'm going to scrap my question and rewrite it so that it's not taking up a lot of space and making a mess... thanks again.
Dr.Dredel