A couple of years ago I wrote a blog poston how to upload a file with formidable. I had the chance to write the upload function again, and found multer to be much easier to use. Here’s another beginner example.
Install those modules into your Node project with
npm install --save express multer
2. Code
app. Js
const express = require('express'); const multer = require('multer'); const upload = multer({ dest: 'uploads/' // this saves your file into a directory called "uploads" }); const app = express(); app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); // It's very crucial that the file name matches the name attribute in your html app.post('/', upload.single('file-to-upload'), (req, res) => { res.redirect('/'); }); app.listen(3000);
-----------
index.html
<html lang="en"> <head> <title>Simple Multer Upload Example</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <form action="/" enctype="multipart/form-data" method="post"> <input type="file" name="file-to-upload"> <input type="submit" value="Upload"> </form> </body> </html>
This example saves your file into the file system.
Read the multer documentation to do different kinds of uploads.
1. SetupInstall those modules into your Node project with
npm install --save express multer
2. Code
app. Js
const express = require('express'); const multer = require('multer'); const upload = multer({ dest: 'uploads/' // this saves your file into a directory called "uploads" }); const app = express(); app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); // It's very crucial that the file name matches the name attribute in your html app.post('/', upload.single('file-to-upload'), (req, res) => { res.redirect('/'); }); app.listen(3000);
-----------
index.html
<html lang="en"> <head> <title>Simple Multer Upload Example</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <form action="/" enctype="multipart/form-data" method="post"> <input type="file" name="file-to-upload"> <input type="submit" value="Upload"> </form> </body> </html>
3. Run
Go to
localhost:3000 to try it out
No comments:
Post a Comment