如何使用httpClient将文件上载到特定文件夹

时间:2015-01-21 11:14:55

标签: java php file-upload httpclient

我正在尝试使用Apache HttpClient将zip文件上传到FTP服务器。

我的java代码是这样的:

public void doFileUpload(String Localfile, String myurl) {
HttpClientBuilder builder = HttpClientBuilder.create();
HttpClient httpClient = builder.build();

HttpPost httpPost = new HttpPost(myurl);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.addBinaryBody("file", new File(Localfile));

final HttpEntity entity = entityBuilder.build();
System.out.println(entity.getContentLength());

httpPost.setEntity(entity);
        try {
            HttpResponse response = httpClient.execute(httpPost);
            System.out.println(response.toString());
            System.out.println("Success");
        } catch (IOException  ex) {
            System.out.println("Failed"+ex);
            Logger.getLogger(FileUpload.class.getName()).log(Level.SEVERE, null, ex);
        }

在我的php文件中:

if (!empty($_FILES["file"]["name"])) {
        $dat = time();
    $file_name=$_FILES["file"]["name"];
    $temp_name=$_FILES["file"]["tmp_name"];
        $target_path = $file_name."-".$dat;

if (is_uploaded_file($temp_name)) {
  echo "File ". $target_path ." uploaded successfully.\n";
  move_uploaded_file ($temp_name, $target_path);
} else {
  echo "Possible file upload attack: ";
  echo "filename '". $temp_name . "'.";
  print_r($_FILES);
}
}

如果我将文件上传到我的php文件所在的文件夹,这样可以正常工作。但在我的情况下,用户会将他们的文件上传到他们自己的文件夹。示例:用户A将文件上传到myftp/upload/A/,或者用户B将文件上传到myftp/upload/B/目标文件夹是从用户端定义的。我可以手动为所有用户创建文件夹,并在每个文件夹中放置一个php文件。但是我怎么能用一个php文件呢?

0 个答案:

没有答案