Using Nuxt and Cloudinary to seamlessly upload images from the client side directly to the Cloudinary platform

Is there a way to directly upload images from my Nuxt (vue) app to Cloudinary without involving a server? I've been searching for information on how to accomplish this but haven't found any concrete solutions.

    <v-file-input
      v-else
      v-model="imageFile"
      accept="image/*"
      @change="onImageChange"
    >
    </v-file-input>
</template>

JavaScript

   methods: {
    this.isLoading = true;
      try {
        const response = awai UPLOAD TO CLODINARY
        this.$emit('change', response);
      } catch (e) {
        console.log(e);
      } finally {
        this.isLoading = false;
      }
}

}

Answer №1

For a demonstration of HTML5 Upload using Cloudinary, you can refer to the CodePen example provided below.

If you are working with Nuxt, there shouldn't be any issues as this process occurs post-rendering.

Please visit the following link for the CodePen example: CodePen Cloudinary Example

Here is the JavaScript code extracted from the CodePen:

JS

const cloudName = 'demo';
const unsignedUploadPreset = 'doc_codepen_example';

var fileSelect = document.getElementById("fileSelect"),
  fileElem = document.getElementById("fileElem"),
    urlSelect = document.getElementById("urlSelect");

fileSelect.addEventListener("click", function(e) {
  if (fileElem) {
    fileElem.click();
  }
  e.preventDefault(); // prevent navigation to "#"
}, false);

urlSelect.addEventListener("click", function(e) {
  uploadFile('https://res.cloudinary.com/demo/image/upload/sample.jpg')
  e.preventDefault(); // prevent navigation to "#"
}, false);

// Drag and Drop functionality
function dragenter(e) {
  e.stopPropagation();
  e.preventDefault();
}

function dragover(e) {
  e.stopPropagation();
  e.preventDefault();
}

dropbox = document.getElementById("dropbox");
dropbox.addEventListener("dragenter", dragenter, false);
dropbox.addEventListener("dragover", dragover, false);
dropbox.addEventListener("drop", drop, false);

function drop(e) {
  e.stopPropagation();
  e.preventDefault();

  var dt = e.dataTransfer;
  var files = dt.files;

  handleFiles(files);
}

// Function to upload file to Cloudinary
function uploadFile(file) {
  var url = `https://api.cloudinary.com/v1_1/${cloudName}/upload`;
  var xhr = new XMLHttpRequest();
  var fd = new FormData();
  xhr.open('POST', url, true);
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

  document.getElementById('progress').style.width = 0; // Reset progress bar

  xhr.upload.addEventListener("progress", function(e) {
    var progress = Math.round((e.loaded * 100.0) / e.total);
    document.getElementById('progress').style.width = progress + "%";

    console.log(`fileuploadprogress data.loaded: ${e.loaded},
  data.total: ${e.total}`);
  });

  xhr.onreadystatechange = function(e) {
    if (xhr.readyState == 4 && xhr.status == 200) {
      var response = JSON.parse(xhr.responseText);
      var url = response.secure_url;
      var tokens = url.split('/');
      tokens.splice(-2, 0, 'w_150,c_scale');
      var img = new Image();
      img.src = tokens.join('/');
      img.alt = response.public_id;
      document.getElementById('gallery').appendChild(img);
    }
  };

  fd.append('upload_preset', unsignedUploadPreset);
  fd.append('tags', 'browser_upload'); // Optional - add tag for image admin in Cloudinary
  fd.append('file', file);
  xhr.send(fd);
}

// Handle selected files
var handleFiles = function(files) {
  for (var i = 0; i < files.length; i++) {
    uploadFile(files[i]); 
  }
};

HTML:

<div id="dropbox">
  <h1>Client-Side Upload to Cloudinary with JavaScript</h1> Learn more in this blog post - <a href="https://cloudinary.com/blog/direct_upload_made_easy_from_browser_or_mobile_app_to_the_cloud">Direct upload made easy from browser or mobile app to the cloud</a>

  <form class="my-form">
    <div class="form_line">
      <h4>Upload multiple files by clicking the link below or by dragging and dropping images onto the dashed region</h4>
      <div class="form_controls">
        <div class="upload_button_holder">
          <input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
          <a href="#" id="fileSelect">Select some files</a>&nbsp;&nbsp;
          <a href="#" id="urlSelect">URL Upload</a>
        </div>
      </div>
    </div>
  </form>
  <div class="progress-bar" id="progress-bar">
    <div class="progress" id="progress"></div>
  </div>
  <div id="gallery" />
</div>
</div>

Answer №2

To get started, begin by installing the Nuxt Cloudinary package from this source Introduction to Nuxt Cloudinary. Follow the provided setup instructions carefully to ensure proper configuration. Then, navigate to the following resource Nuxt Cloudinary Upload. Remember to pay attention to the usage of uploadPreset as an object key in the documentation; make sure to adjust it to upload_preset to avoid any potential errors. After completing the setup process, paste the snippet of code below:

<script>
export default {
  methods: {
    async selectFile(e) {
      const file = e.target.files[0];

      /* Verify file existence */
      if (!file) return;

      /* Create a reader */
      const readData = (f) => new Promise((resolve) => {
        const reader = new FileReader();
        reader.onloadend = () => resolve(reader.result);
        reader.readAsDataURL(f);
      });

      /* Read data */
      const data = await readData(file);

      /* Upload the converted data */
      const instance = this.$cloudinary.upload(data, {
        folder: 'upload-examples',
        uploadPreset: 'your-upload-preset',
      })
    }
  }  
}
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An issue occurred: TypeError - Unable to access the 'subscribe' property of an undefined object during a POST HTTP request in Angular [8]

I'm currently attempting to send data to a REST API using Postman. I am encountering an issue where I receive the error "Cannot read property 'subscribe' of undefined" when making a POST HTTP call, as shown in the console log: https://i.sta ...

Update the picture dynamically when hovering

Is there a way to change an image randomly when hovering over it? The hover effect is working fine, but the image does not revert back when the mouse moves out. Any suggestions on how to fix this? var arr = ["020", "053", "306", "035", "930"]; function ...

Creating header menus with section labels in Windows 8 Metro can be easily accomplished by utilizing Javascript

Is there a way to create a navigation menu in Windows 8 Metro JavaScript that includes header menus and section labels, similar to the example shown below? ...

Issue with nested views in Angular UI-Router not displaying properly

The issue I'm facing is that the template <h1>HELLO</h1> is not loading into the nested ui-view in analysis.client.view.html. However, the ui-view in the analysis.client.view.html file is being loaded successfully. I've tried naming t ...

Different approach to iterating through elements

Looking to implement .forEach instead of a traditional for loop? 'use strict'; var score = (function(){ function updateScore() { for(var i = 0; i < arguments.length; i++) { this.score += arguments[i]; ...

What is the best way to show instructions immediately upon receipt of a response?

I'm currently working on developing a website similar to ChatGpt using the OpenAI API for GPT. However, there is a delay in generating responses with GPT taking a few seconds. As a result, my code only displays the instruction once the response from G ...

The Material UI React radio buttons have the ability to modify the value of previous buttons

I'm facing an issue with my Material UI React Stepper Component that contains a group of radio buttons. The problem is that changing the radio button in one step affects the selected value in previous and future steps. I've experimented with diff ...

What are the differences between using the open prop and conditionally rendering a Material-UI Modal component?

Is there a difference in using the open prop or conditionally rendering Material-UI's Modal component and its built components? The closing transition may be lost, but are there any performance advantages when dealing with multiple Modals? Example wi ...

Passing data from child component to parent component using Vue emit

Having some trouble figuring out why this code isn't functioning as expected, despite following the same examples I've seen. Parent.vue <tree-select class="ml-5 tree-select" :nodes="all" :value=&q ...

Trouble with the filter function in the component array

I am facing an issue with creating and deleting multiple components. I have successfully created the components, but for some reason, I am unable to delete them when I click on the "delete" button. state = { data: '', todoCard: [], id ...

Leveraging viewbag information in combination with jQuery JSON techniques

I have a desire to utilize my ViewBag within a JavaScript array. After researching on using viewbag with jquery asp.net mvc 3, I believe I found the code that suits my needs: @model MyViewModel <script type="text/javascript"> var model = @Html. ...

Discover how to access the DOM after AngularJS directive rendering is finished

Looking to create a unique scroll pane component using an AngularJS directive? Check out this jsfiddle example for a basic prototype. Here is the concept behind my custom scroll pane: Directice code snippet: myApp.directive('lpScrollPane', ...

How can I send a current variable through PHP?

I have a pressing deadline and I need some guidance before moving forward. Can someone please advise if what I'm attempting is feasible or if there's a quicker solution? I encountered some problems with an accordion menu, so as a temporary fix, ...

What is the proper way to declare and utilize a constant list within a component template in NuxtJs?

Can someone help me with using itemList in a template? The itemlist is a static list, but I am unsure of where to declare it and how to export it to the template. <template> <table class="table table is-striped is-narrow is-fullwidth" ...

Increase ng-grid row height dynamically based on content without any external plugins or reliance on jQuery

I came across a similar question on this topic at Angular ng-grid row height However, none of the solutions provided there meet my requirements. If I use CSS to fix the issue, it impacts the page's responsiveness and disrupts ng-grid's header fu ...

How do I navigate to the homepage in React?

I am facing an issue with my routes. When I try to access a specific URL like http://localhost:3000/examp1, I want to redirect back to the HomePage. However, whenever I type in something like http://localhost:3000/***, I reach the page but nothing is dis ...

What is the best way to insert an <image> tag into the SVG DOM?

Currently, I am facing an issue with adding a background image to the generated SVG DOM in my web page. The user interacts by drawing an SVG doodle on top of a jpg image using Raphael. After the user is done with their drawing, I want to enable them to sa ...

failure of text to display in d3.append

Having trouble displaying a tooltip on a rectangle in d3js. The tooltip renders, but the text doesn't show up. After researching similar issues, I discovered that I cannot directly append 'text' to a 'rect' element. I tried addin ...

Please click the provided link to display the data in the div. Unfortunately, the link disappearance feature is currently not

What I'm Looking For I want the data to be displayed when a user clicks on a link. The link should disappear after it's clicked. Code Attempt <a href="javascript:void(0);" class="viewdetail more" style="color:#8989D3!important;">vi ...

Mastering the Art of Configuring Filters in Plupload

I am using plupload with a unique feature that allows me to select and upload files with extensions that are not defined in the settings. For instance, I can upload .rar or .txt files without explicitly defining them in the filters. $(".uploadDocs").cli ...