Dino Geek, try to help you

How to upload files with Node.js and Multer?


Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files.

Below is an example of how to upload files using Node.js and Multer:

Firstly, you need to install Multer and then include it in your project:

```
npm install multer —save
```

```
var express = require(‘express’);
var multer = require(‘multer’);
var app = express();
```

Then, decide how multer should process incoming files. To store files on disk, use `multer.diskStorage` function, where you can determine the destination and filename for incoming files:

```
var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, ‘./uploads’) //specify the folder path where files get stored }, filename: function (req, file, cb) { cb(null, file.fieldname + ‘-’ + Date.now()) //specify the name of the file }
})

var upload = multer({ storage: storage })
```

To handle post requests of incoming files use:

```
app.post(‘/upload’, upload.single(‘myFile’), function (req, res, next) { // req.file is the ‘myFile’ file // req.body will hold the text fields, if there were any
})
```

In this case, `upload.single(‘myFile’)` is the middleware for handling single file uploads where ‘myFile’ is the name of the file input field in the form.

Finally, start your server using:

```
app.listen(3000, function () { console.log(‘Server started on port 3000’);
});
```

Now, if you send a POST request to the ‘/upload’ route with a file attached with the key ‘myFile’, it will be saved to the disk at the ‘./uploads’ path with its fieldname and current datestamp as the filename.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use