skip to Main Content

I have been trying to upload files to a Flask API with the javascript fetch API.

I am forming the request like this:

    let file = new FormData();
    let imageFile = document.getElementById("select-image").files[0];
    file.append("file", imageFile);
    fetch('http://localhost:5000/image-file',
      {
        method: 'PUT',
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': token
        },
        body: file
      })
      .then(async http => {
        let response = http.text();
        if (http.ok) {
          console.log("created")
          postImageData(text);
        }
        else {
          return response.then(response => {throw new Error(response);})
        }
      })
      .catch(error => {
        console.log(error);
      })

but when I do request.files in flask, the object is empty, and request.files["file"] returns an error.

Inspecting the request, the payload looks like this:

------WebKitFormBoundaryG7nrDvgPSk3FSRUs
Content-Disposition: form-data; name="file"; filename="2480_books2.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryG7nrDvgPSk3FSRUs--

My file upload element looks like this:

<input id="select-image" name="image" type="file"/><br/>

Can I access the file from the request as it is, or is there a problem with the request itself?

2

Answers


  1. Chosen as BEST ANSWER

    Managed to solve it - in case anyone else comes across this issue it turns out the solution is extremely simple: just remove the Content-Type header from the fetch request, as the type is handled automatically.


  2. "Note that files will only contain data if the request method was POST, PUT or PATCH and the that posted to the request had enctype="multipart/form-data". It will be empty otherwise."

    Perhaps enctype="multipart/form-data" is missing from the form tag

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search