cft

How to Upload Audio and Video to Cloudinary in Nodejs

Why do you need to upload to the cloud?


user

Idris Olubisi

a year ago | 7 min read

Even after reading the documentation, I ran across a few problems when uploading audio and video to cloudinary. Although I read some publications online, such as StackOverflow, the methodology differs and appears to be 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.

Prerequisite

  • A working knowledge of JavaScript
  • A basic understanding of NodeJS

What is Cloudinary?

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, all the way to delivery.

Without installing any extra software, you can effortlessly upload photographs, audio and videos to the cloud and automate clever transformations of those material using Cloudinary. Cloudinary seamlessly provides your media via a fast content delivery network (CDN) designed according to industry best practices.

Why do you need to upload to the cloud?

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 you to focus on solving complex business logic.

Create a New Project

To open visual studio code, navigate to any Directory of your choice on your pc. In the terminal, type:

code.

Note: code . won't work if you don't have visual studio code installed on your system

Create a directory and initialize npm by typing the following command:

  • Windows power shell
mkdir cloudinary-audio-video-project
cd cloudinary-audio-video-project
npm init -y
  • Linux
mkdir cloudinary-audio-video-project
cd cloudinary-audio-video-project
npm init -y

Create the necessary files

We'll install several dependencies like multer, express dotenv cloudinary and development dependency 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 you notice, our file has some environment variables. You can create a new .env file if you haven't and add your variable 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.

Audio Upload

Before we get started with the upload, kindly make sure you have created a Free Cloudinary Account. Then, copy the API KEY, CLOUD NAME, and SECRET on your 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);
}
);
});
});

//...

Remember to update your .env file with the keys you saved earlier on our dashboard.

CLOUDINARY_CLOUD_NAME=
CLOUDINARY_API_KEY=
CLOUDINARY_API_SECRET=

Now Let's test. 👇👇👇

Video Upload

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

Conclusion

We learned about Cloudinary and how to upload both audio and video to cloudinary from our NodeJS application.

Happy coding!

Upvote


user
Created by

Idris Olubisi

Software Engineer | Technical Writer | Content Creator


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles