Multer uploading array of files fail

11,334

Solution 1

My problem was I append the array of files to the FD I uploaded as fd.append(files, fileList) and what I should have done is a for loop that append each file object from the array of files to the FD with a field name of files. Thank you all for your answers.

Solution 2

I assume you able to take file object array, if you print file array, console.log(files) => [File, File, File, .... etc]. Then, Take your files and fields, create FromData Object and append all things you needed to send to the server as below. Make sure put you 'Content-Type' as undefined, your browser will assign boundary for you else backend will attempt to reject the request.

this.uploadFileToUrl = function(file, title, text, uploadUrl){
    var payload = new FormData();

    payload.append("title", title);
    payload.append('text', text);

    for(var x = 0; x<file.length; x++) {
        payload.append('myfile', file[x]);
    }

    console.log(payload);

    return $http({
        url: uploadUrl,
        method: 'POST',
        data: payload,
        //assign content-type as undefined, the browser
        //will assign the correct boundary for us
        headers: { 'Content-Type': undefined},
        //prevents serializing payload.  don't do it.
        transformRequest: angular.identity
    });
}

Solution 3

From what i understand from your description is that you are making use of the upload.array method to accept multiple files from the same input field. Make sure you specify the fieldname for this method as specified in the documentation:

.array(fieldname[, maxCount])

Accept an array of files, all with the name fieldname. Optionally error >out if more than maxCount files are uploaded. The array of files will be stored in req.files.

What that means is, if you have an input like:

<input type="file" name="foobar" multiple>

Then on the server side use:

var upload = require('multer')({ dest:'uploads/' });
upload.array('foobar');
Share:
11,334
h. Oo
Author by

h. Oo

Updated on June 17, 2022

Comments

  • h. Oo
    h. Oo almost 2 years

    I have an array of file objects that is sent to the server. "files[0] = (file object), files[1]= ... " Multer doesn't recognized its field name and "request.files" is empty but "request.body is with the array of files.

  • Michael Hirschler
    Michael Hirschler almost 7 years
    Posting a code sample, does not explain how it works. Can you please write some thoughts, how this works and how this might help answering the question?
  • Harshan Morawaka
    Harshan Morawaka almost 7 years
    Thank you Michael, i got it and i explained the answer.
  • Snoopy
    Snoopy about 5 years
    You just saved me a bunch of time my friend.
  • Holiday
    Holiday about 2 years
    Thank you kindly sport from the future!