'API Platform / React - uploading file not working
I'm trying to send an image to my API with React using a formData and Axios but my request in my custom controller shows null. When I use PostMan my api accepts the image fine.
In the headers of my axios request I have to add a boundary when without, it tells me a "missing boundary" error, however in the doc I can't find any info about that...
This is my request with Axios
const bodyFormData = new FormData()
bodyFormData.append('name',info.name)
bodyFormData.append('description',info.description)
bodyFormData.append('price',info.price)
bodyFormData.append('file', info.image,"image.jpg")
await Axios({
method: "post",
url: "http://127.0.0.1:8000/api/products/upload",
data: bodyFormData,
headers: { 'Content-Type': `multipart/form-data; boundary=${bodyFormData._boundary}` },
}).then(response=>console.log(response.data));
and my custom controller (works with PostMan)
<?php
namespace App\Controller;
use App\Entity\Product;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class UploadProductController extends AbstractController
{
private $manager;
public function __construct(EntityManagerInterface $manager){
$this->manager = $manager;
}
public function __invoke(Request $request)
{
$uploadedFile = $request->files->get('file');
if (!$uploadedFile) {
throw new BadRequestHttpException('"file" is required');
}
dd($uploadedFile);
}
}
the answer is always "file is required" with React but with PostMan I have a file...
Solution 1:[1]
Two possible solutions:
- Try to send with XMLHttpRequest. Add the header
'X-Requested-With': 'XMLHttpRequest'
. It works for me with Axios but on a standalone Symfony project (without API-Platform). I'm not sure if it can work in your case, but you can try. - Another solution is to remove headers. I had the same problem on a API-Platform project with VueJS and Fetch API in front. I don't remember where I see that, it seems API-Platform has a problem with the multipart/form-data. Your request will look like:
await Axios({
method: "post",
url: "http://127.0.0.1:8000/api/products/upload",
data: bodyFormData,
}).then(response=>console.log(response.data));
It's weird, but it's what I'm doing, and it works fine. Sorry for the lack of explanation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |