03-Jan-2023
.
Admin
Hello Friends,
For this blog tutorial we will be going through the steps of uploading several images in one export package using Node.js, Express.js, and Cloudinary. This article does assume that you already have a working knowledge with Node.js and Javascript, so we will not discuss the concept of persisting data in a database.
We will write a function to create image storage for the images that are to be uploaded. Then we will create a function to let us be able to upload images using the multer package. We will then create a route for us to hit the URL and test the package for uploading the image.
Step 1: Create Node JS App
In this step, open your terminal and execute the following command to create node js app:
mkdir my-app
cd my-app
npm init -y
Step 2: Install Express and Multer Dependencies
In this step, open your terminal again and execute the following command to install express and multer dependencies in your node js app:
npm install express multer --save
npm install sharp --save
Step 3: Create Server.js File
In this step, you need to create a server.js file and add the following code to it:
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'uploads/');
},
filename: function(req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
var upload = multer({ storage: storage })
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.post('/', upload.array('multi-files'), (req, res) => {
res.redirect('/');
});
app.listen(3000);
Step 4: Create Multiple File/Image Upload Form
In this step, create an index.html file to resize the image before uploading to the node js app. So, add the following HTML code into it:
<!DOCTYPE html>
<html lang="en">
<head>
<title>How to upload multiple image files in Node.js using Multer? - Nicesnippets.com</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>How to upload multiple image files in Node.js using Multer? - Nicesnippets.com</h1>
<form action="/" enctype="multipart/form-data" method="post">
<input type="file" name="multi-files" accept='image/*' multiple>
<input type="submit" value="Upload">
</form>
</body>
</html>
Click to know more about the express.
Step 5: Start Node Express Js App Server
You can use the following command to run the development server:
//run the below command
npm start
After running this command open your browser and hit
http://127.0.0.1:3000/
I hope it can help you...
#Node JS