文件上传通过Java的lib Apache的百科全书简明的例子 [英] Concise example of file upload via Java lib Apache Commons

查看:186
本文介绍了文件上传通过Java的lib Apache的百科全书简明的例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经打消了我费解,严重畸形的问题,以便它不从非常工整,正确答案下方减损。由于找到一个在线的例子做这个令人难以置信的共同任务(令人惊讶的)困难,我希望得到号Yoni数多了起来,蜱他的回应。

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

如何使用Apache.Commons将文件上传到某个目的地。我用它在Android和上传到PHP脚本,但很明显,它可以从任何Java程序以及任何基于HTTP的监听工作。

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.

推荐答案

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

  • 我不认为你需要的内容处置一部分,用于另一个方向(当浏览器下载文件,并需要知道如何处理它)。
  • getParams.setParameter 是可选的。您也可以直接在HttpClient的实例进行设置。
  • AFAIK,设置请求头的顺序是无关紧要的,只要他们,然后再设定请求体均设置。
    • 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.
    • 这篇关于文件上传通过Java的lib Apache的百科全书简明的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆