简体   繁体   English

发送多部分表单数据后,php响应标头中未显示任何内容

[英]nothing displayed in php response header after sending multipart form data

I have the following files. 我有以下文件。 Nothing is displayed in the Response header of developer tools. 开发人员工具的“响应”标头中未显示任何内容。 I am expecting the variables related to files and post in my accept.php page. 我期望与文件相关的变量并在我的accept.php页面中发布。

I can see console.log(formData); 我可以看到console.log(formData); getting printed but console.log(returndata); 得到打印但console.log(returndata);

1) send.php file 1) send.php文件

<?php

echo ' 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<script type="text/javascript" src="file.js"></script>

<form id="data" enctype="multipart/form-data">
      <input type="hidden" name="id" value="123" readonly="readonly">
      User Name: <input type="text" name="username" value=""><br />
      Profile Image: <input name="profileImg[]" type="file" /><br />
      Display Image: <input name="displayImg[]" type="file" /><br />
      <button  type = "button" onclick="submitFileTest()">Submit Button  </button>
    </form>';

?>

2) file.js 2) file.js

function submitFileTest() { 


          //grab all form data  
          var formData = new FormData($(this)[0]);

          console.log("Form Data Test");
          console.log(formData);

          $.ajax({
            url: 'accept.php',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (returndata) {
              //alert(returndata);
              console.log(returndata);
            }
          });




 }

3) accept.php 3) accept.php

<?php


        if (isset($_POST['id'])) {                      
            $id = $_POST['id'];
            var_dump($id);
            echo $id;
        }


        if (isset($_POST['username'])) {
           $username = $_POST['username'];
           var_dump($username);
           echo $username;
        }


        if (isset($_FILES['profileImg'])) {
            $profileImg = $_FILES['profileImg'];
            var_dump($profileImg);
            echo $profileImg;
        }

        if (isset($_FILES['displayImg'])) {
             $displayImg = $_FILES['displayImg'];
             var_dump($displaying);
             echo $displayImg;
        }

?>

TESTING RESULTS (after using Popmedic answer): 测试结果(使用Popmedic答案后):

Before testing, for displayImg ,I changed the file array value in the following line formData.append('displayImg', $('input[type=file]')[1].files[0]); 在测试之前,对于displayImg ,我在以下行中更改了文件数组值formData.append('displayImg', $('input[type=file]')[1].files[0]); from 0 to 1 as shown below formData.append('displayImg', $('input[type=file]')[1].files[1]); 01 ,如下所示formData.append('displayImg', $('input[type=file]')[1].files[1]);

I am able to see the id value, username value and profileImg value in my php script as shown in the screenshot of console window of IE11 below. 我可以在我的PHP脚本中看到id值, username值和profileImg值,如下面的IE11控制台窗口的屏幕截图所示。 But for some reason, the code is not picking up the second file which is displayImg . 但是由于某种原因,该代码没有选择第二个文件displayImg

在此处输入图片说明

The following is the screenshot of Request body of IE11 showing that for the file displayImg , there is nothing present. 以下是IE11的Request body的屏幕截图,显示了对于文件displayImg ,没有任何内容。

在此处输入图片说明

Clarifications on Popmedic's comments (April 18): 对Popmedic的评论的澄清(4月18日):

I have merged the POST and FILEs results using this solution and got the following in the JSON format: 我已经使用此解决方案合并了POST和FILEs结果,并以JSON格式获得了以下内容:

{"id":"123","username":"123","profileImg":{"name":"Request_body.PNG","type":"image\/png","tmp_name":"C:\\wamp\\tmp\\phpA981.tmp","error":0,"size":15842},"displayImg":{"name":"Request_body.PNG","type":"image\/png","tmp_name":"C:\\wamp\\tmp\\phpA9A1.tmp","error":0,"size":15842}}

I already have a Java webservice working which is accepting a JSON object and storing it in the Oracle database in the form of CLOB. 我已经有一个Java Web服务正在工作,该服务正在接受JSON对象并将其以CLOB形式存储在Oracle数据库中。 So that's the reason I merged and converted into JSON as shown above. 因此,这就是我如上所述合并并转换为JSON的原因。 I would like to include the variable $str value also in the JSON response above obtained from this line of code $str = file_get_contents($_FILES["displayImg"]["tmp_name"]); 我想在上面的JSON响应中也包含变量$str值,该值是从这行代码$str = file_get_contents($_FILES["displayImg"]["tmp_name"]); so that in addition to the above JSON, I could also include the file contents to the webservice and that Java webservice will make sure that it's inserted into the Oracle database. 这样,除了上面的JSON之外,我还可以将文件内容包含到Web服务中,并且Java Web服务将确保将其插入到Oracle数据库中。 eventually my cuRL request would look like this: 最终,我的cuRL请求将如下所示:

                      $curl = curl_init();
                      curl_setopt_array($curl, array(
                      CURLOPT_PORT => "9090",
                      CURLOPT_URL => "http://localhost:9090/myJavaWebservice/rest/somepath/insertDataToDB",
                      CURLOPT_RETURNTRANSFER => true,
                      CURLOPT_ENCODING => "",
                      CURLOPT_MAXREDIRS => 10,
                      CURLOPT_TIMEOUT => 30,
                      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                      CURLOPT_CUSTOMREQUEST => "POST",
                      CURLOPT_POSTFIELDS => $_POST["myData"],
                      CURLOPT_HTTPHEADER => array(
                        "Cache-Control: no-cache",
                        "Content-Type: application/json"

                        ),
                      ));

                    $response_post_march22 = curl_exec($curl);
                    $err = curl_error($curl);

                    curl_close($curl);

                    if ($err) {
                      echo "cURL Error #:" . $err;
                    } else {
                      echo $response_post_march22;
                    } 

I already have the above curl request working and inserting the data into the database but now instead of myData which is a JSON object , I would be passing the new JSON, I created above after merging including the file content obtained using the $str variable so that everything can be stored into the database. 我已经有了上面的curl请求,并将数据插入数据库中,但是现在代替了myData它是一个JSON object ,我将传递新的JSON,我是在合并后创建的,其中包括使用$str变量获取的文件内容,因此一切都可以存储到数据库中

Maybe set something in the header for you to see... 也许在标题中设置一些内容供您查看...

if (isset($_POST['id'])) {                      
    $id = $_POST['id'];
    header ("ID: $id");
    var_dump($id);
    echo $id;
}else {
    header ("ID-Present: Nope");
}


if (isset($_POST['username'])) {
    $username = $_POST['username'];
    header ("User-Name: $username");
    var_dump($username);
    echo $username;
}else {
    header ("User-Name-Present: Nope");
}


if (isset($_FILES['profileImg'])) {
    $profileImg = $_FILES['profileImg'];
    header ("Profile-Image-Present: Yep");
    var_dump($profileImg);
    echo $profileImg;
} else {
    header ("Profile-Image-Present: Nope");
}

if (isset($_FILES['displayImg'])) {
    $displayImg = $_FILES['displayImg'];
    header ("Display-Image-Present: Yep");
    var_dump($displayImg);
    echo $displayImg;
} else {
    header ("Display-Image-Present: Nope");
}

UPDATED TO SHOW HOW TO SET QUERY PARAM(S) 更新以显示如何设置查询参数

If you want the headers to be something other then "Nope," you need to send those values in your javascript AJAX request like so: 如果您希望标头不是“ Nope”,则需要在javascript AJAX请求中发送这些值,如下所示:

function submitFileTest() { 
    var formData = new FormData();
    formData.append('id', $('[name="id"]').val());
    formData.append('username', $('[name="username"]').val());
    // Attach file
    formData.append('profileImg', $('input[type=file]')[0].files[0]);
    formData.append('displayImg', $('input[type=file]')[1].files[0]); 
    console.log("Form Data Test");
    console.log(formData);

    $.ajax({
        url: 'accept.php',
        type: 'POST',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        success: function (returndata) {
          //alert(returndata);
          console.log(returndata);
        }
      });
}

UPDATED TO USE get_file_post_data FROM OTHER SOLUTION 通过其他解决方案更新为使用get_file_post_data

I believe if you change the other solutions get_file_post_data function (I had to remove some of the useless code from this function, it annoyed me too much) to: 我相信,如果您更改其他解决方案的 get_file_post_data函数(我不得不从该函数中删除一些无用的代码,会使我非常恼火)至:

function get_file_post_data() {
    $files = array();
    $post = $_POST;
    foreach ($_FILES as $key_a => $data_a) 
        foreach ($data_a as $key_b => $data_b) {
            // Add this --->
            if ($key_b == 'tmp_name')
                $files['data'][$key_a] = base64_encode(file_get_contents($data_b));
            // <--- end
            $files[$key_b][$key_a] = $data_b;
        }
    foreach ($files as $type => $data) merge_file_post_data($type, $data, $post);
    return $post;
}

Then when you convert into JSON with something like json_encode(get_file_post_data(), JSON_PRETTY_PRINT); 然后,当您使用json_encode(get_file_post_data(), JSON_PRETTY_PRINT);类的内容转换为JSON时json_encode(get_file_post_data(), JSON_PRETTY_PRINT); , you will have JSON like so: ,您将拥有JSON,如下所示:

{
    "id": "123",
    "username": "kevin",
    "profileImg": {
        "name": "suggestions@1.png",
        "type": "image\/png",
        "data": "iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAVlpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS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5CYII=",
        "tmp_name": "\/private\/var\/tmp\/phpBU7D0c",
        "error": 0,
        "size": 941
    },
    "displayImg": {
        "name": "suggestions@2.png",
        "type": "image\/png",
        "data": "iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM\/rhtAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAVlpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDUuNC4wIj4KICAgPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICAgICAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgICAgICAgICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iPgogICAgICAgICA8dGlmZjpPcmllbnRhdGlvbj4xPC90aWZmOk9yaWVudGF0aW9uPgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KTMInWQAABKNJREFUWAm9mE+IVmUUxsfUSE1z\/ItSKDRRLQzUJEkmQhqw2rgRwtoULQo3ga3CxbRS3AiCQguXs3CRqIgEIjYjEU1GFEHOxjFwSqQazb+NTvb8vnue2535\/r33fkMHnnve97znPPe8533fe+\/3zeoqJ4\/IfZYwGWF90m8KG4Q1wiqBsSvCZeEb4aQwLCBzBMYf0plpmV0g3K72dwI3SsEZ+W0WECbIRJME5xQhOWaO\/xHhXcEypMY54WfhZhiXSL8gvCasDxuqX\/iUhoQk\/6m1Orx4tnPFQyKu2Cm1NyVwb5PPt4U4JmhJLZD96zQEJmEvObndBU\/G2VuASgP31czlkFqO3x\/W4rbJHcs0uBHysWDyD2qWbIk8HqY6RfJU3nJADfO8EcZ2HI6t017a1RoZFyA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ZegUeJ1SK6hkkw8HhZ8Jg2EsfEsVVElf+E0WTSCu8Hnco9fyrlFUhqFj5Y4UEWVZOtBPeFzFU9X+XYpIf6e7DAvuPE\/ul8JZgKfralqT\/BVPW\/p9Rsv1pAAAAAElFTkSuQmCC",
        "tmp_name": "\/private\/var\/tmp\/php3kezNJ",
        "error": 0,
        "size": 1635
    }
}

If you would like to cut the response time in about half, you can try doing some poorman's threading in PHP... 如果您希望将响应时间减少一半左右,则可以尝试在PHP中进行一些穷人的线程处理 ...

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

相关问题 角度多部分/表单数据表单发送 - Angular multipart/form-data form sending 多部分/表单数据表单使用AngularJS发送数据 - Multipart/form-data form sending data with AngularJS axios 发布请求正在发送请求 header 的 Content-Type: multipart/form-data 导致未定义的 req.body - axios post request is sending a request header of Content-Type: multipart/form-data resulting in undefined req.body 提交后不显示任何内容 - Nothing is displayed after submit Web服务需要JSON,发送多部分表单数据 - Webservice expecting JSON, sending multipart-form data 将多部分表单发送到具有多行数据的后端服务 - Sending multipart form to backend service with multiple rows of data 使用 axios 在 POST 多部分/表单数据请求中发送文件和 json - sending file and json in POST multipart/form-data request with axios 使用multipart / form-data在Reactjs Dropzone中发送文件 - Sending files in Reactjs Dropzone using multipart/form-data 将类对象发送到期望包含多部分数据的Web服务 - Sending a class object to a multipart-form-data-expected web service 在 Angular 7.x 中接收格式化的“multipart/form-data”响应 - Receive formatted 'multipart/form-data' response in Angular 7.x
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM