Android sending image to Server via MultipartEntity - setting Content-type?

后端 未结 5 711
北恋
北恋 2020-12-17 22:18

I\'ve read many many posts about sending an image to the server from an Android app and Content-type-wise, they are divided in three categories:

a) they dont set the

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 23:12

    Use this code to upload image file

    HttpClient client = new DefaultHttpClient();
    HttpPost postMethod = new HttpPost("http://localhost/Upload/index.php");
    File file = new File(filePath);
    MultipartEntity entity = new MultipartEntity();
    FileBody contentFile = new FileBody(file);
    entity.addPart("userfile",contentFile);
    StringBody contentString = new StringBody("This is contentString");
    entity.addPart("contentString",contentString);
    
    postMethod.setEntity(entity);
    client.execute(postMethod);
    

    and in PHP use this code to receive

    $uploads_dir = '/Library/WebServer/Documents/Upload/upload/'.$_FILES['userfile']['name'];
    if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
        echo $_POST["contentString"]."\n";
        echo  "File path = ".$uploads_dir;
        move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $uploads_dir);
    } else {
        echo "\n Upload Error";
        echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
        print_r($_FILES);
    }
    

提交回复
热议问题