使用Java应用程序将文件上载到Web服务器
我发现了这个小代码片段,可以使用ApacheCommonsFileUpload库上传文件。但是,它不会将文件作为多部分/表单数据上载,而是作为普通POST数据上载。有什么建议我应该怎么做才能使用PHP的move_上传的文件来保存文件吗使用Java应用程序将文件上载到Web服务器,java,apache-commons,Java,Apache Commons,我发现了这个小代码片段,可以使用ApacheCommonsFileUpload库上传文件。但是,它不会将文件作为多部分/表单数据上载,而是作为普通POST数据上载。有什么建议我应该怎么做才能使用PHP的move_上传的文件来保存文件吗 HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httppost = new HttpPost("http://www.example.com/upload.php");
HttpClient httpclient = new DefaultHttpClient();
try
{
HttpPost httppost = new HttpPost("http://www.example.com/upload.php");
FileBody bin = new FileBody(new File("/path/to/file"));
StringBody comment = new StringBody("A binary file of some kind");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse uploadResponse = httpclient.execute(httppost);
HttpEntity resEntity = uploadResponse.getEntity();
System.out.println(uploadResponse.getStatusLine());
if (resEntity != null)
{
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
}
finally
{
try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {}
}
您使用什么版本的http组件?我用4.1.2对它进行了测试,结果与预期的一样。Commons Logging 1.1.1和FileUpload 1.2.1。FileUpload 1.2.1中不存在您正在使用的类(例如HttpClient)。它们来自ApacheHTTP组件。你用的是哪个版本?好像我用的是4.1.2。问题是该文件不是作为文件上传的,而是作为正常的POST表单数据上传的。