PUT request for file in django-react-redux

Viewed 250

I tried to apply put request in Django-react-redux for the file. What I was trying to do is, the user should have to replace the file using ID filed from put request. I write the following code in django-restframework.

class EarSingleView(APIView):

    parser_classes = (MultiPartParser, FormParser)

    def get(self, request, ear_id, *args, **kwargs):
        ear = Ear.objects.get(pk=ear_id)
        serializer = EarSerializers(ear)
        return Response(serializer.data)

    def delete(self, request, ear_id, *args, **kwargs):
        ear = Ear.objects.get(pk=ear_id)
        ear.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

    def put(self, request, ear_id):
        ear = Ear.objects.get(pk=ear_id)
        serializer = EarSerializers(ear, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

My get request and delete request working perfectly. But in PUT request, If I tried to change the file filed and try to submit, the following error will occur, 400:Bad request. detail: "Multipart form parse error - Invalid boundary in multipart: None"

My form looks like this,

<form onSubmit={this.onSubmit} encType="multipart/form-data">
  <Input
    placeholder="Enter layer name..."
    name="name"
    value={name}
    onChange={this.onChange}
   />

   <input
     type="file"
     name="fileName"
     onChange={this.handleFileChange}
   />
</form>

My form onSubmit event is looks like this,

onSubmit = (e) => {
    e.preventDefault();
    const {
      name,
      file,
    } = this.state;

    const newEARData = {
      id: this.props.idNumber,
      name,
      file,
    };

    axios
    .put(`http://localhost:8000/api/ear/${newEARData.id}`, newEARData, {
      headers: {
        "content-type": "multipart/form-data",
      },
    })
    .then((res) => {
      dispatch({
        type: UPDATE_EAR,
        payload: res.data,
      });
    })
}

get request is looks like this,

 axios
    .get(`http://localhost:8000/api/ear/${id}`)
    .then((res) => {
      dispatch({ type: GET_DETAILED_EAR, payload: res.data });
    })

Please anyone suggest to me what is the best way to replace the file (put request) in the django-react-redux setup?

1 Answers

For passing multipart formdata, you need to pass it via FormData, simple json object won't work

const formData = new FormData();
formData.append('id',this.props.idNumber)
formData.append('name',name)
formData.append('file',file)
axios.put(`http://localhost:8000/api/ear/${this.props.idNumber}`, formData, {
    headers: {
    "content-type": "multipart/form-data",
    },
})
Related