使用请求类型multipart / form-data清空$ _POST和$ _FILES

时间:2014-08-06 13:48:55

标签: php android

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

但我无法在服务器中获取此数据。变量$ _FILES,$ _POST甚至php://输入为空。但数据确实转移到服务器,因为在$ _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

这是我的安卓代码

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);
}

2 个答案:

答案 0 :(得分:1)

也许您已经更改了php.ini参数,例如使enable_post_data_reading=on增加post_max_sizeupload_max_filesize

答案 1 :(得分:0)

不确定您使用的方法,并且未包含服务器端处理文件。错误可能来自任何一个。但试试这个。我首先通过params发送一个文件路径并命名为'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;

?>