How to Upload Images with NuxtJS and Cloudinary

So I got to that moment when you say to yourself: “Can life get any easier than this?” , and I want to show you how to get there too….

…On a project I recently had to upload images to Cloudinary from my Nuxt.js client web app and it was such a breeze and I think its the most minimal way to do it because….

Cloudinary Widget makes it so….

easy to quickly and elegantly upload images to Cloudinary from your Nuxt.js application. This is how I did it:

Assumptions…

  1. You already know how to write a Nuxt.js application
  2. You have a Cloudinary account
  3. You love simplicity

Now lets ….

Dive In

So in the Nuxt page, in which you want to perform the upload let’s say edit-profile.vue, you set the CDN for the Cloudinary widget, like so:

head() { 
    return {
        script: [{src: 'https://widget.cloudinary.com/v2.0/global/all.js'}]
    }
} 

Psst: You can also globally link to the external resource if you want in your nuxt.config.js head section…

Going onward, in my methods object, I created the below method to help with the creation of the widget.

createCloudinaryWidget(){
    const newWidget = cloudinary.createUploadWidget(
        {
            cloudName: 'your_cloud_name_goes_here',
            uploadPreset: 'your_preset_goes_here',
            multiple: false,
            maxFiles: 1,
            cropping:true,
            croppingAspectRatio: 1,
            croppingCoordinateMode: 'face',
            clientAllowedFormats: ['png', gif, 'jpeg']
        },
        (error,result) =>{
            //checking if upload was successfully done!
            if (!error && result && result.event === 'success'){
                console.log(result.info)
                //save url to a server database, or prerform any other logic here
            } 
        }
    )
    return newWidget
},

This method declaration is in my methods object in my Vue Configuration options of the page

Then I call this method like so when a button gets clicked(Using @click to listen to a click event on a button, nothing fancy 😏)

openCloudinaryWidget(){
    const widget = this.createCloudinaryWidget()
    widget.open()
}

The click event handler which is also declared on the methods object

And that’s it! But let’s have some vitamins shall we?

Understanding what the upload widget is and its various configuration options

cloudinary.com : https://cloudinary.com/documentation/upload_widget

Using external resources in NuxtJS: https://nuxtjs.org/faq/

Happy deploying

#vuejs #javascript #vue-js #nuxtjs #Cloudinary

How to Upload Images with NuxtJS and Cloudinary
62.10 GEEK