使用Java应用程序将文件上载到Web服务器

时间:2011-12-30 23:19:11

标签: java apache-commons

我发现这个小代码片段用Apache Commons FileUpload库上传文件。但是,它不会将文件作为multipart / form-data上传,而是将普通POST数据上传。有什么建议我应该如何使用PHP的move_uploaded_file来保存文件?

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) {}
}

0 个答案:

没有答案