空$ _POST和$ _FILES与请求类型的multipart / form-data的 [英] empty $_POST and $_FILES with request type multipart/form-data

查看:150
本文介绍了空$ _POST和$ _FILES与请求类型的multipart / form-data的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Android应用程序发送POST请求到服务器。在这一请求,我想送一些文本数据(JSON)和图片。

但我不能得到这个服务器的数据。变量$ _FILES,$ _ POST,甚至PHP://输入为空。但是数据确实传输到服务器,因为在$ _ SERVER我能找到这样的:

  [REQUEST_METHOD] => POST
[内容] =>的multipart / form-data的;边界= Jq7oHbmwRy8793I27R3bjnmZv9OQ_Ykn8po6aNBj;字符集= UTF-8
[CONTENT_LENGTH] => 53228

有什么问题可以用这个?结果
服务器是nginx的1.1结果
PHP版本5.3.6-13ubuntu3.10结果
file_uploads =在

下面是我的android code

  RequestConfig配置= RequestConfig.custom()
    .setConnectTimeout(30000)
    .setConnectionRequestTimeout(30000)
    .setSocketTimeout(30000)
    .setProxy(getProxy())
    。建立();CloseableHttpClient客户端= HttpClientBuilder.create()
        .setDefaultRequestConfig(配置)
        。建立();HttpPost后=新HttpPost(http://example.com);尝试{    JSONObject的根=新的JSONObject();
    root.put(ID,身份证);    如果(mSettings!= NULL){
        root.put(设置,SettingsJsonRequestHelper.getSettingsJson(mSettings));
    }    。MultipartEntityBuilder建设者= MultipartEntityBuilder.create()setMode(HttpMultipartMode.BROWSER_COMPATIBLE);    文件截图= getScreenshotFile();
    如果(screenshot.exists()){
        builder.addPart(屏幕截图,新FileBody(截图,ContentType.create(图像/ JPEG)));
    }    builder.addTextBody(数据,root.toString(),ContentType.create(文/ JSON,Charset.forName(UTF-8)));    builder.setCharset(MIME.UTF8_CHARSET);
    post.setEntity(builder.build());
}赶上(JSONException E){
    。Logger.getInstance()日志(E);
}尝试{
    HTT presponse响应= client.execute(岗位);
    如果(response.getStatusLine()的getStatus code()== HttpStatus.SC_OK){
        mResponse.setResponse(response.getEntity()的getContent());
    }其他{
        。Logger.getInstance()日志(回应错误code。+ response.getStatusLine()的getStatus code());
    }
}赶上(ClientProtocolException E){
    。Logger.getInstance()日志(E);
}赶上(IOException异常五){
    。Logger.getInstance()日志(E);
}


解决方案

不知道该方法使用的是和你没有包括你的服务器端处理文件。错误可能来自任何一个。不过,试试这个。我首先向它发送一个文件路径通过PARAMS并将其命名为textFileName。

  @覆盖
    保护字符串doInBackground(字符串... PARAMS){
        // 文件路径
        串textFileName =参数[0];
        字符串消息=这是一个多岗;
        字符串结果=;        //设置服务器端脚本文件来处理它
        HttpPost后=新HttpPost(http://10.0.2.2/test/upload_file_test.php);
        档案文件=新的文件(textFileName);        //图像文件和文本添加到建设者
        MultipartEntityBuilder建设者= MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addBinaryBody(uploaded_file,文件,ContentType.DEFAULT_BINARY,textFileName);
        builder.addTextBody(文字,邮件,ContentType.DEFAULT_BINARY);        //括在一个实体,执行,结果得到
        HttpEntity实体= builder.build();
        post.setEntity(实体);
        HttpClient的客户端=新DefaultHttpClient();
        尝试{
            HTT presponse响应= client.execute(岗位);
            读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
                    。response.getEntity()的getContent(),UTF-8));
            串sResponse;
            StringBuilder的S =新的StringBuilder();            而((sResponse = reader.readLine())!= NULL){
                S = s.append(sResponse);
            }
            的System.out.println(回应:+ S);        }赶上(ClientProtocolException E){
            // TODO自动生成catch块
            e.printStackTrace();
        }赶上(IOException异常五){
            // TODO自动生成catch块
            e.printStackTrace();
        }
        返回消息;
    }

服务器端的PHP是这样的:

 < PHP
$ target_path1 =上传/;
/ *原始文件名添加到我们的目标路径。
结果是上传/ filename.extension* /
$状态=;
如果(使用isset($ _ FILES [uploaded_file])){回声文件存在!//如果(使用isset($ _ POST [文字])){
//回声的消息文件存在!$ _ POST [文字]。
//}$ target_path1 = $ target_path1。基本名($ _FILES ['uploaded_file'] ['名']);如果(move_uploaded_file($ _ FILES ['uploaded_file'] ['tmp_name的值'],$ target_path1)){
    $状态=第一个文件。基本名($ _FILES ['uploaded_file'] ['名'])。
    已上传。
}
其他{
    $状态=有上传文件的错误,请重试!
    $状态=文件名。基本名($ _FILES ['uploaded_file'] ['名']);
    $状态=target_path:。$ target_path1;
}}其他{回声中的文件目录中没有;
}$阵列[身份] =状态:$地位;
$ JSON_OBJECT = json_en code($数组);
回声$ JSON_OBJECT;?>

I'm trying to send post request from android application to server. In this request I want to send some text data (json) and picture.

But I can't get this data in server. Variables $_FILES, $_POST and even php://input is empty. But data is really transferred to server, because in $_SERVER I can find this:

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

What is the problem can be with this?
server is nginx 1.1
PHP Version 5.3.6-13ubuntu3.10
file_uploads = On

Here is my android code

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

解决方案

Not sure of the method you are using and you did not include your server side processing file. Error may be from either one. But try this. I first send it a file path through the params and named it '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;
    }

Server side php looks like:

<?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;

?>

这篇关于空$ _POST和$ _FILES与请求类型的multipart / form-data的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆