richardgirges / express-fileupload

Simple express file upload middleware that wraps around busboy
MIT License
1.52k stars 261 forks source link

Unable to upload files when trying with Javascript. #296

Closed simplenotezy closed 2 years ago

simplenotezy commented 2 years ago

I am trying to upload files to my backend server with this library, and I am facing a few issues.

The HTML form I have tested, and that works fine - so I know the backend is set up correctly. However, I am using Javascript to handle my form submission.

My payload looks like this:

image image

My javascript code to post looks like this:

const data = new FormData();

Object.entries(files).forEach(([fieldName, files]) => {
    data.append(fieldName, files[0]);
    // fieldName: the input name
    // files = FileList (https://developer.mozilla.org/en-US/docs/Web/API/FileList)
});

fetch({
    url: `files/upload`,
    method: "POST",
    headers: {
        "Content-Type": "multipart/form-data",
    },
    body: data,
})

To best of my knowledge, about code should work. I have also tried different variations with and without the headers (which some recommend I don't set, and some recommend I do).

On the backend req.files will always be undefined.

If using a traditional

, req.files will not be undefined.

Anybody know what could be wrong? I've been through multiple similar issues in this repo, but to no avail.

When enabling the debug option, this is what I see in console:

OPTIONS /files/upload 204 1.115 ms - 0
Express-file-upload: Request is not eligible for file upload!
req.fields: undefined
POST /files/upload 422 4.197 ms - 37
simplenotezy commented 2 years ago

What solved it for me was to ensure I did NOT set any Content-Type header. In my case my baseQuery would automatically set Content-Type if none was provided, and this is fixed now.