Search code examples
djangodjango-rest-frameworkfetchmultipartform-data

DjangoRestFramework ParserError "Multipart form parse error - Invalid boundary in multipart: None"


Frontend

<body>
  <input id="fileRef" type="file" />
  <button onclick="push">Push</button>

  <script>
    function push() {
      const file = fileRef.files[0];
      const formData = new FormData();
      formData.append('image', file, file.name);

      fetch('http://127.0.0.1:8000/api/item/', {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        method: 'POST',
        body: formData
      });
    }
  </script>
</body>

Backend

from rest_framework.parsers import MultiPartParser

class ItemViewSet(ModelViewSet):
    ...
    parser_classes = [MultiPartParser]

The above is the minimal implementation of the bug, when I send the request, it will generate such an error: Multipart form parse error - Invalid boundary in multipart: None

Request headers, payload

enter image description here

enter image description here

I spend a long time and don't know how to solve ;)

I tried change Content-Type like this

'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'

But it doesn't work, My expectation is that django can correctly parse and successfully accept the file


Solution

  • I thought it was a problem with django at first, but then I found out that my request on the front end was incorrect ;)

    WebAPI fecth, when sending multipart/form-data, there is no need to manually set the Content-Type attribute in request headers!!!

    If the request body is FormData, the browser will automatically add Content-Type: multipart/form-data to the headers and add the correct boundary.

    I found this while browsing through these articles, anyway, my problem was solved successfully~

    I’m here to reply to a question I asked before, maybe someone will come here with the same question as me in the near future, hahahahaha...