繁体   English   中英

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

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

我正在尝试将发布请求从 android 应用程序发送到服务器。 在这个请求中,我想发送一些文本数据(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 = 开

这是我的安卓代码

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;

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM