DEV Community

Raphael Machado
Raphael Machado

Posted on

Upload images with Cloudinary, MongoDB and Express.

We will have to create a middleware that uploads an image to cloudinary and returns it's image url

Create an account in cloudinary and choose programmable media.

Now go back to editor and create 3 variables in dotev file with these informations: CLOUD_NAME, API_KEY, API_SECRET.
You get that from cloudinary dashboard.

cloudinary connection

Create a folder 'utils' with a 'cloudinary.js' file.

cloudinary.js code

Create a 'controller' folder with a 'cloudinaryMiddleware.js' file.

middleware code
Now you just have to import and place it in your REST API like this:

rest api code

Top comments (4)

Collapse
 
ecyrbe profile image
ecyrbe • Edited

You should add that you also need to setup a form-data middleware (like multer) else your example will not work.

Collapse
 
rm0909 profile image
Raphael Machado • Edited

Now i'm confused.
I used fileReader in the frontend and it worked without multer.

filereader

axios post

Collapse
 
ecyrbe profile image
ecyrbe • Edited

Oh i see, thanks for the clarification.

This code just send the image as a dataURI (base64 encoded file) that cloudinary understands.

Your frontend example is a good complement to your article.

Just to clarify what i meant with multer.
Usually in frontend, to send images, you usually use a form submitted by the browser itself.

This way the file uploaded is optimised (it's really sent as a binary file with multipart/form-data content-type). No base64 transformation, less bandwith used, less compute used, etc.
But express do not understand multipart/form-data content natively, you need to use a middleware like multer to read this content.

Since cloudinary also supports binary Buffers, usually people will send it in binary format.

Hope i clarified also my comment.

Thread Thread
 
rm0909 profile image
Raphael Machado

thank you for the explanation!