Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Java应用程序将文件上载到Web服务器_Java_Apache Commons - Fatal编程技术网

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

使用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");

我发现了这个小代码片段,可以使用ApacheCommonsFileUpload库上传文件。但是,它不会将文件作为多部分/表单数据上载,而是作为普通POST数据上载。有什么建议我应该怎么做才能使用PHP的move_上传的文件来保存文件吗

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表单数据上传的。