通过php在java上传文件

时间:2015-07-05 06:11:39

标签: java php

我正在尝试使用java在我的php服务器上传文件,但每次运行代码时我的httprequest失败,我不知道它的原因是什么,首先我认为它可能是由multipartEnttity方法引起的我的参数我之前是空的,但现在在填充之后,同样的问题仍然是ocurrs ....

    //this is my java code

    String path="E:\\upload.txt";
    HttpClient hc=new DefaultHttpClient();
    hc.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost hp=new HttpPost("http://localhost/shoolPHP/uploadFile.php");
    File f=new File(path);
    MultipartEntity me=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    ContentBody cf=new FileBody(f);
    me.addPart("userfile", cf);
    hp.setEntity(me);
    System.out.println("executing request" +hp.getRequestLine());
    HttpResponse hr=hc.execute(hp);
    HttpEntity he=hr.getEntity();

    if(!(hr.getStatusLine().toString()).equals("HTTP/1.1 200 OK")){
        System.out.println("Uploaded");
    }
    else{
        System.out.println("Failed");


    }
    System.out.println(hr.getStatusLine());
    if (he != null) {
        System.out.println(EntityUtils.toString(he));
    }
    if (he != null) {
        he.consumeContent();
    }
    hc.getConnectionManager().shutdown();

//这是更正的PHP代码

  <?php

  $uploads_dir='/Home';
  if(is_uploaded_file($_FILES['userfile']['tmp_name'])){
   $dest=$_FILES['userfile']['name'];
  echo "File" .$_FILES['userfile']['name'] ."uploaded file successfully to
  $uploads_dir/$dest";

  move_uploaded_file ($_FILES['userfile'] ['tmp_name'],  "$uploads_dir/$dest");
  } else {
  echo "Possible file upload attack: ";
  echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
  print_r($_FILES);
  }
  ?>

//这些是新警告

执行requestPOST http://localhost/shoolPHP/uploadFile.php HTTP / 1.1 上传 HTTP / 1.1 200好的 Fileupload.txtuploaded文件成功到 /Home/upload.txt
警告:move_uploaded_file(/Home/upload.txt):无法打开流: C:\ xampp \ htdocs \ shoolPHP \ uploadFile.php 中没有此类文件或目录第 9
警告:move_uploaded_file():无法将 \ xampp \ tmp \ phpB374.tmp'移动到 C:\ xampp \ htdocs \ shoolPHP中的'/Home/upload.txt' uploadFile.php 9

1 个答案:

答案 0 :(得分:0)

您的代码说:

if(!(hr.getStatusLine().toString()).equals("HTTP/1.1 200 OK")){
  ^^^
   +--- Notice the ! (not)

将其更改为:

if((hr.getStatusLine().toString()).equals("HTTP/1.1 200 OK")){

如果状态为200,则上传确实正常,因此必须等于该状态行才能显示“已上传”。你的代码说它必须与说“Uploaded”

不同