Uploading multiple files with Node.js

1

I'm trying to upload multiple files with Node.js, but I can not do the server part.

I'm using ExpressJS as a framework, and if need be I can use other packages to facilitate this task.

For the time being, I'm using express.bodyParser() and inspecting the upload with console.log(req.files) , but this only shows me one of the files.

On the client input is marked as multiple and form is with enctype="multipart/form-data" .

    
asked by anonymous 16.06.2014 / 20:17

1 answer

1

To upload multiple files, the name attribute of input must be followed by [] , so files will be sent as array

<form method="post" action="" enctype="multipart/form-data">
  <input type="file" name="nome[]" multiple />
</form>

If you use the name attribute with no array notation, the server will replace the previous file name with the most recent one, using the notation, you inform the server that you want to have multiple fields with the same name, and these are added in array .

Complementing with the server part:

On the server, the files are in an array within req.files.nome[0] for example. Note that the array is the first item of req.files.nome , not the object itself. Inspecting req.files.nome[0] I get an object with a structure like this:

[ { fieldName: 'nome[]',
    originalFilename: 'Arquivo1.png',
    path: 'caminho/local/temporario/do/arquivo.png',
    headers:
     { 'content-disposition': 'form-data; name="nome[]"; filename="Arquivo1.
png"',
       'content-type': 'image/png' },
    ws:
     { _writableState: [Object],
       writable: true,
       domain: null,
       _events: [Object],
       _maxListeners: 10,
       path: 'caminho/local/temporario/do/arquivo.png',
       fd: null,
       flags: 'w',
       mode: 438,
       start: undefined,
       pos: undefined,
       bytesWritten: 1008705,
       closed: true },
    size: 1008705,
    name: 'Arquivo1.png',
    type: 'image/png' }, // (outros arquivos...)
}
    
16.06.2014 / 21:31