To upload and save an image within a Node.js application, you may use the multer middleware for multipart/form-data handling, which is essentially utilized for uploading files. Here’s a step-by-step guide:
Step 1: Prepare Your Node.jsProject
Initialize a new project:
mkdir image-upload cd image-upload npm init -y
Install the required dependencies:
npm install express multer
- mkdir image-upload:
- This command makes a new directory (folder) called image-upload. The mkdir command is short for “make directory”.
- cd image-upload:
- This command moves into the newly created image-upload directory. The cd command is short for “change directory”.
- npm init -y:
- This command creates a new Node.js project in the image-upload directory.
- npm is short for Node Package Manager, which is a command-line tool to manage Node.js packages.
- init is used to make a package.json file, which holds metadata about the project and its dependencies.
- The -y flag automatically responds to all questions with a “yes”, employing the default values for the package.json file. This is a time-saver because it bypasses the interactive questions that ask for things like the project name, version, description, etc.
- In short, this snippet initializes a new Node.js project by making a directory, moving into it, and creating a package.json file with default values.
Step 2: Build the Server
Create a new file named server.js and configure an Express server:
const express = require('express'); const multer = require('multer'); const path = require('path'); const app = express(); const port = 3000; // Set storage engine const storage = multer.diskStorage({ destination: './uploads/', filename: function (req, file, cb) { cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)); } }); // Initialize upload variable const upload = multer({ storage: storage, limits: { fileSize: 1000000 }, // Limit file size to 1MB fileFilter: function (req, file, cb) { checkFileType(file, cb); } }).single('myImage'); // Check File Type function checkFileType(file, cb) { const filetypes = /jpeg|jpg|png|gif/; const extname = filetypes.test(path.extname(file.originalname).toLowerCase()); const mimetype = filetypes.test(file.mimetype); if (mimetype && extname) { return cb(null, true); } else { cb('Error: Images Only!'); } } // Public folder app.use(express.static('./public')); app.post('/upload', (req, res) => { upload(req, res, (err) => { if (err) { res.send('Error: ' + err); } else { if (req.file == undefined) { res.send('Error: No File Selected!'); } else { res.send('File Uploaded: ' + req.file.filename); } } }); }); app.listen(port, () => console.log(`Server started on port ${port}`));
const express = require('express'); const multer = require('multer'); const path = require('path');
These lines import the express
, multer
, and path
modules.
const app = express(); const port = 3000;
Initializes an Express application and sets the port number to 3000.
const storage = multer.diskStorage({ destination: './uploads/', filename: function (req, file, cb) { cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)); } });
Configures the storage engine for multer to specify the upload destination and filename format.
const upload = multer({ storage: storage, limits: { fileSize: 1000000 }, // Limit file size to 1MB fileFilter: function (req, file, cb) { checkFileType(file, cb); } }).single('myImage');
Initializes multer
with storage settings, file size limit, and file filter function. Handles single file uploads with the field name myImage
.
function checkFileType(file, cb) { const filetypes = /jpeg|jpg|png|gif/; const extname = filetypes.test(path.extname(file.originalname).toLowerCase()); const mimetype = filetypes.test(file.mimetype); if (mimetype && extname) { return cb(null, true); } else { cb('Error: Images Only!'); } }
Defines a function to validate the uploaded file’s type, ensuring only image files are accepted.
app.use(express.static('./public'));
Configures Express to serve static files from the public
directory.
app.post('/upload', (req, res) => { upload(req, res, (err) => { if (err) { res.send('Error: ' + err); } else { if (req.file == undefined) { res.send('Error: No File Selected!'); } else { res.send('File Uploaded: ' + req.file.filename); } } }); });
Sets up a POST route /upload
to handle file uploads. Displays appropriate messages based on upload success or failure.
app.listen(port, () => console.log(`Server started on port ${port}`));
Starts the Express server on the specified port (3000) and logs a message to the console.
This code sets up a simple server using Express and Multer to handle image file uploads and store them in the uploads
directory.
Step 3: Create the Frontend
Create a new directory named public and a file within it named index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Image Upload</title> </head> <body> <h1>Upload an Image</h1> <form action="/upload" method="POST" enctype="multipart/form-data"> <input type="file" name="myImage" /> <input type="submit" value="Upload" /> </form> </body> </html>
This HTML document provides a simple form for uploading an image. Users can select an image file and click the “Upload” button to send the file to the server for processing.
Step 4: Run the Server
Run the server:
node server.js
When you run the command node server.js, you are instructing Node.jsto execute the code within the server.js file. This usually starts the server, listens for incoming requests, and performs any defined actions based on those requests.
Now, go to your browser and access http://localhost:3000. You will see the form to upload an image. When you submit the form, the image will be stored in the uploads directory.