1
votes

I'm trying to upload a file using api platform file upload. I'm using React-redux with redux-saga to make this request, but the server keeps throwing bad request response.

Api platform documentation says the following for making the request:

This endpoint accepts standard multipart/form-data-encoded data, but not JSON data. You will need to format your request accordingly.

My Saga: I tried appending my uploaded file to formData and use that as body for my request.

 let data = new FormData();
 data.append("file", action.payload.file)

 const fileResponse = yield call(
   fetch,
   `${api.url}/api/media_objects`,
   {
     method: 'POST',
     mode: 'no-cors',
     body: data,
     headers: { 'content-type': 'multipart/form-data' }
   }
 );
 return console.log(fileResponse);

This is the api platform example request for posting a new media object

curl -X POST "https://api.myroute/api/media_objects" -H "accept: application/ld+json" -H "Content-Type: multipart/form-data" -F "[email protected];type=image/jpeg"

Api platform keeps returning a 400 error, which refers to invalid input. Any idea how the valid input should look like?

For my media object entity I followed the api platform documentation, so it looks exactly the same as in the docs

2

2 Answers

1
votes

Details matter

headers: { 'content-type': 'multipart/form-data' }

It should be

headers: { 'Content-Type': 'multipart/form-data' }

There is no 'content-type', only 'Content-Type' header is defined (RFC) and widely accpeted.

0
votes

I had a very similar issue recently (I can't remember the exact error), with API Platform (and the MediaObject entity), and React - redux (but no redux-saga).

I was able to fix it by removing the header part of my request :

headers: { 'content-type': 'multipart/form-data' }

So my new request looked exactly like that in my case :

const formData = new FormData();
    formData.append('file', file);
    return fetch(id, {
      method: 'POST',
      body: formData
    })
    ...

I don't really know why, but it did the trick. Maybe it is handled automatically since we send a FormData object.

Hope it can work for you too !