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.).
Your answer is correct and will probably solve the question problem, but I think it’s worth explaining why
{ outrosDados, imagem }
not being working. :-)– Luiz Felipe