简体   繁体   中英

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

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

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

Firstly, note that you can only append binary data or a string through the FormData.append() method. Providing an object as you are means that toString() will be called on it, so the value will actually become "[object Object]" .

To fix this you'll need to manually JSON.stringify the object before you append() it:

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() .

However, it would be much simpler to just append the values to the FormData object directly. 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:

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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