Upload multiple files with Node.js

Asked

Viewed 765 times

1

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

I am using Expressjs as a framework, and if necessary I can use other packages to facilitate this task.

For now, I’m using the express.bodyParser() and inspecting the upload with console.log(req.files), but that only introduces me to one of the files.

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

  • 1

    The name of input this one with clasps input type="file" name="nome[]" ..., to be sent as array?

  • @abfurlan No, this is necessary?

  • 1

    Yes, for multiple upload yes.

  • @abfurlan I will make the change. Post this as a response, if it works I approve.

  • Let me know if it works then put.

  • I once had the same problem with PHP. After a couple of days going through the entire code, I found out that I just added brackets to the input to work. HTML trolled full with this requirement.

  • 2

    @Kazzkiq The same thing happened to me in PHP, so I suggested to try, this could be it.

  • It worked, adds the answer I accept, and complement with the server-side part.

Show 3 more comments

1 answer

1


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

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

If used the attribute name unrated array, the server will replace the previous file name to the latest one, using the notation, you inform the server that you want to have several fields with the same name, and these are added in a 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, and 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...)
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.