# How to Upload Audio and Video to Cloudinary in Nodejs

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.

## Prerequisite
- A working knowledge of JavaScript
- A basic understanding of NodeJS

## What is Cloudinary?

[Cloudinary](https://cloudinary.com) 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.

## Why do we 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 us to focus on solving complex business logic.

## Creating a new Project

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

```Bash
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:

- 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 as shown below

![Screenshot 2021-05-22 at 18.22.35.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1621704227104/l41BDST2c.png)

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.

```Javascript
"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 starting the upload, we need to create a Free [Cloudinary Account](https://cloudinary.com). 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. 👇👇👇

![Cloudinary audio upload](https://cdn.hashnode.com/res/hashnode/image/upload/v1621720340034/v-iGLJTVZ.png)

## 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 👇👇👇

![Cloudinary video upload](https://cdn.hashnode.com/res/hashnode/image/upload/v1621721112977/iRSb0aujv.png)

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](https://github.com/Olanetsoft/cloudinary-audio-video-project)

## Conclusion

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

Happy coding!

## Resources

[Cloudinary](https://cloudinary.com/blog/node_js_file_upload_to_a_local_server_or_to_the_cloud)

[NodeJS](https://nodejs.org/en/)

[ExpressJS](https://expressjs.com/)


I'd love to connect with you at [Twitter](https://twitter.com/olanetsoft) | [LinkedIn](https://www.linkedin.com/in/olubisi-idris-ayinde-05727b17a/) | [GitHub](https://github.com/Olanetsoft)

See you in my next blog article. Take care!!!
