空$_POST和$_FILES,请求类型为multipart/form-data


empty $_POST and $_FILES with request type multipart/form-data

我正在尝试从android应用程序发送post请求到服务器。在这个请求中,我想发送一些文本数据(json)和图片。

但是我无法在服务器中获取此数据。变量$_FILES, $_POST甚至php://input都是空的。但是数据实际上是传输到服务器的,因为在$_SERVER中我可以找到这个:

[REQUEST_METHOD] => POST
[CONTENT_TYPE] => multipart/form-data; boundary=Jq7oHbmwRy8793I27R3bjnmZv9OQ_Ykn8po6aNBj; charset=UTF-8
[CONTENT_LENGTH] => 53228  

这有什么问题?
服务器是nginx 1.1
PHP版本5.3.6-13ubuntu3.10
file_uploads = On

这是我的android代码

RequestConfig config = RequestConfig.custom()
    .setConnectTimeout(30000)
    .setConnectionRequestTimeout(30000)
    .setSocketTimeout(30000)
    .setProxy(getProxy())
    .build();
CloseableHttpClient client = HttpClientBuilder.create()
        .setDefaultRequestConfig(config)
        .build();
HttpPost post = new HttpPost("http://example.com");
try {
    JSONObject root = new JSONObject();
    root.put("id", id);
    if (mSettings != null) {
        root.put("settings", SettingsJsonRequestHelper.getSettingsJson(mSettings));
    }
    MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    File screenshot = getScreenshotFile();
    if (screenshot.exists()) {
        builder.addPart("screenshot", new FileBody(screenshot, ContentType.create("image/jpeg")));
    }
    builder.addTextBody("data", root.toString(), ContentType.create("text/json", Charset.forName("UTF-8")));
    builder.setCharset(MIME.UTF8_CHARSET);
    post.setEntity(builder.build());
} catch (JSONException e) {
    Logger.getInstance().log(e);
}
try {
    HttpResponse response = client.execute(post);
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        mResponse.setResponse(response.getEntity().getContent());
    } else {
        Logger.getInstance().log("response error. Code " + response.getStatusLine().getStatusCode());
    }
} catch (ClientProtocolException e) {
    Logger.getInstance().log(e);
} catch (IOException e) {
    Logger.getInstance().log(e);
}

也许你有改变php.ini参数,如enable_post_data_reading=on增加post_max_sizeupload_max_filesize

不确定您正在使用的方法,并且您没有包含服务器端处理文件。错误可能来自任何一方。但是试试这个。我首先通过参数发送一个文件路径,并将其命名为"textFileName"。

    @Override
    protected String doInBackground(String... params) {
        // File path
        String textFileName = params[0];
        String message = "This is a multipart post";
        String result =" ";
        //Set up server side script file to process it
        HttpPost post = new HttpPost("http://10.0.2.2/test/upload_file_test.php");
        File file = new File(textFileName);
        //add image file and text to builder
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addBinaryBody("uploaded_file", file, ContentType.DEFAULT_BINARY, textFileName);
        builder.addTextBody("text", message, ContentType.DEFAULT_BINARY);
        //enclose in an entity and execute, get result
        HttpEntity entity = builder.build();
        post.setEntity(entity);
        HttpClient client = new DefaultHttpClient();
        try {
            HttpResponse response = client.execute(post);
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent(), "UTF-8"));
            String sResponse;
            StringBuilder s = new StringBuilder();
            while ((sResponse = reader.readLine()) != null) {
                s = s.append(sResponse);
            }
            System.out.println("Response: " + s);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return message;
    }

服务器端php如下:

<?php
$target_path1 = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$status = "";

if(isset($_FILES["uploaded_file"])){
echo "Files exists!!";
//  if(isset($_POST["text"])){
//  echo "The message files exists! ".$_POST["text"];
//  }
$target_path1 = $target_path1 . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)) {
    $status= "The first file ".  basename( $_FILES['uploaded_file']['name']).
    " has been uploaded.";
} 
else{
    $status= "There was an error uploading the file, please try again!";
    $status.= "filename: " .  basename( $_FILES['uploaded_file']['name']);
    $status.= "target_path: " .$target_path1;
}
}else{
echo "Nothing in files directory";

}
$array["status"] = "status: ".$status;
$json_object = json_encode($array);
echo $json_object;
?>