Image upload React Axios and PHP

Asked

Viewed 1,017 times

1

I need to make a posting system that includes image and post data with Reactjs, Axios and PHP(yes, php).

No Reactjs

const post = async (formData) => {
    const image = new FormData()
    image.append('imageFile', formData.imageFile[0])

    const config = {
        'Content-Type': 'multipart/form-data',
    }

    await api.post('informations/createInformation', image, config)
        .then((response) => {
            console.log(response.data)
        })
} // post

In PHP I can recover the file by accessing the variable superglobal $_FILES:

public function createInformation(): void
{
    print_r($_FILES);
} // createInformation

The code above prints:

Array 
(
    [imageFile] => Array 
    (
        [name] => teste.png
        [type] => image/svg+xml
        [tmp_name] => /opt/lampp/temp/php6BLbIr
        [error] => 0
        [size] => 22315
    )
)

Using Axios to request the PHP api, you cannot access it from the superglobal variable $_POST, it is only possible to recover the data as follows:

$post = json_decode(file_get_contents('php://input'), true, 512, JSON_THROW_ON_ERROR);

However, to send the image in the request, it is not possible to place it inside a Javascript object, just placing the image alone as post data:

Works

await api.post('informations/createInformation', imagem, config)

Doesn’t work

await api.post('informations/createInformation', { outrosDados, imagem }, config)

The second way, the server receives the array $_FILES empty, and the first way I can’t send the post data along with the image.

What I need is a post with the image and the post data (user, title, etc.).

2 answers

1

Let’s go in pieces:

First we created a function to pass to Base64 the image and mandala in the API:

//Author James Harrington 2014 modified by Doctorspeppers
function base64(file){
  var coolFile = {};
  function readerOnload(e){
    var base64 = btoa(e.target.result);
    coolFile.base64 = base64;
    return coolFile
  };

  var reader = new FileReader();
  reader.onload = readerOnload;

  var file = file[0].files[0];
  coolFile.filetype = file.type;
  coolFile.size = file.size;
  coolFile.filename = file.name;
  reader.readAsBinaryString(file);
}

After that we implemented in code:

await api.post('informations/createInformation', { outrosDados, base64(imagem) }, config)

On the server side we make the following change

<?php 
$imagem = base64_decode($_POST['imagem']);
?>

1


You can add text information (title, user) to the Formdata object.

const frm = new FormData()
frm.append('imageFile', formData.imageFile[0])
frm.append('titulo', 'Título')

*Use the print_r in the superglobal $_REQUEST to validate the received request.

  • 1

    Your answer is correct and will probably solve the question problem, but I think it’s worth explaining why { outrosDados, imagem } not being working. :-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.