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.
Create a folder 'utils' with a 'cloudinary.js' file.
Create a 'controller' folder with a 'cloudinaryMiddleware.js' file.
Now you just have to import and place it in your REST API like this:
Top comments (4)
You should add that you also need to setup a form-data middleware (like multer) else your example will not work.
Now i'm confused.
I used fileReader in the frontend and it worked without multer.
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.
thank you for the explanation!