Skip to content

Instantly share code, notes, and snippets.

@ross-u
Forked from 1travelintexan/cloudinary-setup.md
Created July 19, 2024 07:42
Show Gist options
  • Save ross-u/a1ea573e33da5e118e9396ea4582d1d1 to your computer and use it in GitHub Desktop.
Save ross-u/a1ea573e33da5e118e9396ea4582d1d1 to your computer and use it in GitHub Desktop.
Cloudinary React (module-3)

1. Cloudinary account setup

Go to this link https://cloudinary.com/ and create your cloudinary account, verify your email and go through or skip the initial questions

After you are done you should be able to see the following in your dashboard:

  • Cloud Name
  • API key
  • API Secret

These 3 elements are unique to you and will need them to use cloudinary. You will need to add them to your .env file.

In your .env file:

CLOUD_NAME=<your-cloudinary-name>
CLOUD_API_KEY=<your-cloudinary-key>
CLOUD_API_SECRET=<your-cloudinary-secret>

Make sure you have the correct .env syntax. You don't need to use quotes for the strings.

2. Package installation

Install the following 3 npm packages: cloudinary, multer and multer-storage-cloudinary by running the following code in your terminal

npm i cloudinary multer multer-storage-cloudinary

3. Cloudinary config setup

Create a file in the middlewares folder called cloudinary.config.js and add the following code:

// the following 3 packages are needed in order for cloudinary to run
const cloudinary = require('cloudinary').v2;
const { CloudinaryStorage } = require('multer-storage-cloudinary');
const multer = require('multer');

// your three cloudinary keys will be passed here from your .env file
cloudinary.config({
  cloud_name: process.env.CLOUD_NAME,
  api_key: process.env.CLOUD_API_KEY,
  api_secret: process.env.CLOUD_API_SECRET
});

const storage = new CloudinaryStorage({
  cloudinary,
  folder: 'bananarama', // The name of the folder in cloudinary . You can name this whatever you want
  allowedFormats: ['jpg', 'png'],
  // params: { resource_type: 'raw' }, => add this is in case you want to upload other type of files, not just images
  filename: function (req, res, cb) {
    cb(null, res.originalname); // The file on cloudinary will have the same name as the original file name
  }
});

module.exports = multer({ storage });

4. Frontend setup

Make sure in your frontend you have a form with the following specifications

Put an input of type file into your form
<input type="file" name="image" />
Then in the onSubmit of the form, add a new FormData and append each property that you need to submit
Note: The image is inside e.target.<name on your input>.files[0]
It is 'files' with an 's' because there could be more than one, and use index [0] to access it
   const image = e.target.image.files[0];
    const formData = new FormData();
    formData.append("imageUrl", image);
    formData.append("name", name);
    formData.append("email", email);
    formData.append("password", password);
After you have your formData added, you can submit it in a post request.

IMPORTANT:

  • the action "/upload" can be different but needs to match your route url. See next section.
  • the input name "imageUrl" can be different but needs to match the targeted name in your route. See sext section.

5. Cloudinary route handle

Go to the post route where you want to receive an image/file to store in cloudinary.

Asides from your regular require (express, routes, models) require your cloudinary.config.js by adding the following line:

const uploader = require('../middlewares/cloudinary.config.js');

This is how your route should look like:

router.post('/upload', uploader.single("imageUrl"), (req, res, next) => {
    // the uploader.single() callback will send the file to cloudinary and get you and obj with the url in return
    console.log('file is: ', req.file)
    
    if (!req.file) {
      console.log("there was an error uploading the file"
      next(new Error('No file uploaded!'));
      return;
    }
    
    // You will get the image url in 'req.file.path'
    // Your code to store your url in your database should be here
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment