Concise example of file upload via Java lib Apache

2020-03-06 04:01发布

问题:

[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:

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.