简体   繁体   English

在ajax调用中使用FormData发送JSON对象和文件,并在PHP中访问json对象

[英]sending JSON object along with file using FormData in ajax call and accessing the json object in PHP

I am trying to send json object along with a file in ajax call as follows 我试图在ajax调用中发送json对象和文件,如下所示

Javascript 使用Javascript

$('#btn').on('click', function(){
    var file_data = $('#imgFile').prop('files')[0];
    var form_data = new FormData();
    let jsonObj = {
        'label1':'value1'
    };
    form_data.append('file', file_data);
    form_data.append('json', jsonObj);//json object which I am trying to send
    $.ajax({
        url: 'uploader.php',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,
        type: 'post',
        success: function(php_script_response){
            console.log(php_script_response);
        }
    });
});

and in PHP I am able to retrieve the file sent in ajax call successfully but I dont know how to access the json object sent along with that file 在PHP中我能够成功检索ajax调用中发送的文件,但我不知道如何访问与该文件一起发送的json对象

PHP PHP

<?php
if ( 0 < $_FILES['file']['error'] ) {
    echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
    $file_ext=strtolower(end(explode('.',$_FILES['file']['name'])));
    move_uploaded_file($_FILES['file']['tmp_name'], 'uploadedFiles/1.' . $file_ext);
    echo $_POST['json'];
}

please let me know how to retrive the json object in php 请让我知道如何在PHP中检索json对象

Firstly, note that you can only append binary data or a string through the FormData.append() method. 首先,请注意您只能通过FormData.append()方法追加二进制数据或字符串。 Providing an object as you are means that toString() will be called on it, so the value will actually become "[object Object]" . 提供一个对象意味着将在其上调用toString() ,因此该值实际上将变为"[object Object]"

To fix this you'll need to manually JSON.stringify the object before you append() it: 要修复此问题,您需要在append()之前手动JSON.stringify对象:

let obj = {
    'label1':'value1'
};
form_data.append('file', file_data);
form_data.append('json', JSON.stringify(obj));

Then in your PHP you can deserialise the JSON using json_decode() . 然后在PHP中,您可以使用json_decode()对JSON进行反序列化。

However, it would be much simpler to just append the values to the FormData object directly. 但是,直接将值附加到FormData对象会简单得多。 That way you don't need to manually serialize/deserialize anything: 这样您就不需要手动序列化/反序列化任何东西:

form_data.append('file', file_data);
form_data.append('label1', 'value1');
form_data.append('foo', 'bar');

Then in your PHP: 然后在你的PHP中:

var label = $_POST['label'];
var foo = $_POST['foo'];

Try it like this: 试试这样:

$.ajax({
    url: 'uploader.php',
    cache: false,
    contentType: false,
    processData: false,
    data: form_data+"&json="+jsonObj,
    type: 'post',
    success: function(php_script_response){
        console.log(php_script_response);
    }
});

The PHPp code should then work with $_POST['json'] 那么PHPp代码应该与$ _POST ['json']一起使用

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

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