04-Jan-2023
.
Admin
Hello Friends,
In this article, we will go through the steps involved in uploading images to the cloud using Node.js, and we will be using Cloudinary as our cloud storage.
There are three main ways of handling file uploads in Node.js: saving the images directly to your server, saving the image’s binary data or base64 string data to your database, and using Amazon Web Service (AWS) S3 buckets to save and manage your images.
Step 1: Create Node Express js App
Execute the following command on the terminal to create the node js app:
mkdir my-app
cd my-app
npm init -y
Step 2: Install express and Multer dependencies
Execute the following command on the terminal to install express and busboy dependencies:
npm install express multer body-parser --save
npm install sharp --save
Step 3: Create Server.js File
Create server.js file and import express, multer, and path dependencies in server.js; as shown below:
var express = require("express");
var multer = require('multer');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).single('userPhoto');
app.post('upload-avatar',function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
app.listen(3000,function(){
console.log("Working on port 3000");
});
Step 4: Start Node Express Js App Server
Execute the following command on the terminal to start the node express js server:
//run the below command
npm start
After running this command open your browser and hit
http://127.0.0.1:3000/upload-avatar
Step 5: Upload File using Node js Rest Apis
To upload files using rest APIs; So open postman for sending HTTP multipart/form-data requests: as shown below picture:
I hope it can help you...
#Node JS