How to Upload Audio and Video to Cloudinary in Nodejs

Software Engineer | Developer Advocate | Technical Writer | Content Creator
Search for a command to run...

Software Engineer | Developer Advocate | Technical Writer | Content Creator
Hi Pooja thanks for reaching out. I have a few confirmations
where exactly did you add the "const { path } = req.file; // file becomes available" in the codebase, this matters because it's only available after the actual upload is done.
can you share a link to the repo for additional troubleshooting if option1 did not fix it.
okat i will shareOlubisi Idris Ayinde yes i will share you link of repo
Thank you Olubisi Idris Ayinde for the amazing blog! Enjoyed every bit of it! Great expanation! Cloudinary was super new to me and this blog made me learn more of it! This is super helpdul in my future projects! Thanks Olubisi Idris Ayinde, Keep the amazing content coming! 🔥
Thank you Savio Martin for reading. I am glad you find it useful.
Thank you Catalin Pit I really appreciate your feedback. ☺️
In this series, I'll be sharing incredible content on How- to's, Building and Deploying Applications using Modern Web Technologies.
Record management strategies help maintain firms efficiency and productivity. However, without a thorough, documented records management strategy, organizations experience misunderstandings and data loss. I've seen multiple examples of record mismana...
Step-by-Step Solidity Guide for Beginners: Building Your First Token

Prioritizing Depth Instead of Going with Trends

Cross-chain messaging allows seamless communication and interaction between different blockchain ecosystems, from Ethereum Virtual Machine (EVM)-based chains to Cosmos-based chains. Axelar has long been the best way to connect EVM and Cosmos chains v...

You have millions of unique images in your gallery, each representing a piece of private or personal data stored on your phone. After an incident, you lost your device, but it was returned to you after many months, with claims that the images hadn't ...

Marking a Year of Contributions to Axelar: Pioneering the Future of Interoperability

After reading the documentation, I ran across a few problems uploading audio and video to cloudinary. Although I read some publications online, such as StackOverflow, the methodology differs and appears a little complex. Still, after discovering a technique to upload audio and video smoothly, I decided to share the steps with anyone who might find the blogs and articles challenging to use.
Cloudinary is an end-to-end image and video management system for websites and mobile apps that handle everything from image and video uploads through storage, manipulations, and optimizations way to delivery.
Without installing any extra software, we can effortlessly upload photographs, audio, and videos to the cloud and automate clever transformations of those materials using Cloudinary. Cloudinary seamlessly provides our media via a fast content delivery network (CDN) designed according to industry best practices.
In a nutshell, uploading media to the cloud extends the life of an application. It provides a lot of value right out of the box, allowing us to focus on solving complex business logic.
To open visual studio code, navigate to any Directory of our choice on a pc. In the terminal, type:
code.
Note:
code .won't work if we don't have visual studio code installed on our system.
Create a directory and initialize npm by typing the following command:
mkdir cloudinary-audio-video-project
cd cloudinary-audio-video-project
npm init -y
mkdir cloudinary-audio-video-project
cd cloudinary-audio-video-project
npm init -y
Create the necessary files as shown below

We'll install several dependencies like multer express dotenv cloudinary, and development dependencies like nodemon to restart the server as we make changes automatically.
npm install express multer dotenv cloudinary
npm install nodemon -D
Now let's create our NodeJS Server adding the following snippet to our app.js index.js .env,.
In our app.js.
require("dotenv").config();
const express = require("express");
const app = express();
app.use(express.json());
module.exports = app;
In our index.js.
const http = require("http");
const app = require("./app");
const server = http.createServer(app);
const { API_PORT } = process.env;
const port = process.env.PORT || API_PORT;
// server listening
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});
If we noticed, our file has some environment variables. We can create a new .env file and add the required variables before starting our application.
In our .env.
API_PORT=4001
To start our server, kindly edit the scripts object in our package.json to look like the one shown below and then type the command to start the server safely.
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"test": "echo \"Error: no test specified\" && exit 1"
}
type the command
npm run dev.
Before starting the upload, we need to create a Free Cloudinary Account. Then, copy the API KEY, CLOUD NAME, and SECRET on our dashboard because we will be using them shortly.
Add the snippet below to our file app.js for audio upload.
//...
app.post("/audio/upload", async (req, res) => {
// Get the file name and extension with multer
const storage = multer.diskStorage({
filename: (req, file, cb) => {
const fileExt = file.originalname.split(".").pop();
const filename = `${new Date().getTime()}.${fileExt}`;
cb(null, filename);
},
});
// Filter the file to validate if it meets the required audio extension
const fileFilter = (req, file, cb) => {
if (file.mimetype === "audio/mp3" || file.mimetype === "audio/mpeg") {
cb(null, true);
} else {
cb(
{
message: "Unsupported File Format",
},
false
);
}
};
// Set the storage, file filter and file size with multer
const upload = multer({
storage,
limits: {
fieldNameSize: 200,
fileSize: 5 * 1024 * 1024,
},
fileFilter,
}).single("audio");
// upload to cloudinary
upload(req, res, (err) => {
if (err) {
return res.send(err);
}
// SEND FILE TO CLOUDINARY
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
const { path } = req.file; // file becomes available in req at this point
const fName = req.file.originalname.split(".")[0];
cloudinary.uploader.upload(
path,
{
resource_type: "raw",
public_id: `AudioUploads/${fName}`,
},
// Send cloudinary response or catch error
(err, audio) => {
if (err) return res.send(err);
fs.unlinkSync(path);
res.send(audio);
}
);
});
});
//...
We need to update our .env file with the keys we saved earlier from our Cloudinary dashboard.
CLOUDINARY_CLOUD_NAME=
CLOUDINARY_API_KEY=
CLOUDINARY_API_SECRET=
Now Let's test. 👇👇👇

Let's try out the video upload by adding the snippet below:
//...
app.post("/video/upload", async (req, res) => {
// Get the file name and extension with multer
const storage = multer.diskStorage({
filename: (req, file, cb) => {
const fileExt = file.originalname.split(".").pop();
const filename = `${new Date().getTime()}.${fileExt}`;
cb(null, filename);
},
});
// Filter the file to validate if it meets the required video extension
const fileFilter = (req, file, cb) => {
if (file.mimetype === "video/mp4") {
cb(null, true);
} else {
cb(
{
message: "Unsupported File Format",
},
false
);
}
};
// Set the storage, file filter and file size with multer
const upload = multer({
storage,
limits: {
fieldNameSize: 200,
fileSize: 30 * 1024 * 1024,
},
fileFilter,
}).single("video");
upload(req, res, (err) => {
if (err) {
return res.send(err);
}
// SEND FILE TO CLOUDINARY
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
const { path } = req.file; // file becomes available in req at this point
const fName = req.file.originalname.split(".")[0];
cloudinary.uploader.upload(
path,
{
resource_type: "video",
public_id: `VideoUploads/${fName}`,
chunk_size: 6000000,
eager: [
{
width: 300,
height: 300,
crop: "pad",
audio_codec: "none",
},
{
width: 160,
height: 100,
crop: "crop",
gravity: "south",
audio_codec: "none",
},
],
},
// Send cloudinary response or catch error
(err, video) => {
if (err) return res.send(err);
fs.unlinkSync(path);
return res.send(video);
}
);
});
});
//...
Result 👇👇👇

We can see how seamless it is to upload audio and video to Cloudinary from our nodeJS application.
Here is a link to the Repository on GitHub
We learned about Cloudinary and how to upload both audio and video to Cloudinary from our NodeJS application.
Happy coding!
I'd love to connect with you at Twitter | LinkedIn | GitHub
See you in my next blog article. Take care!!!