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

Is it possible to increment an integer value in jQuery after obtaining the sum result?

Actually, I'm trying to extract the integer value from my input field. For example, if I enter the value 4+5, I want to display the result as 9 in a separate div. However, instead of getting the expected result, I am receiving [object Object]. I&apo ...

Is it possible to implement the same technique across various child controllers in AngularJS?

I am trying to execute a function in a specific child controller. The function has the same name across all child controllers. My question is how can I call this function from a particular controller? Parent Controller: app.controller("parentctrl",functi ...

What could be causing my HTML elements to shift position based on varying screen sizes or zoom levels?

Does anyone else experience their HTML and CSS elements shifting around based on the screen size or zoom level? I have screenshots illustrating this issue. Here is how it currently appears And here is how it's supposed to look ...

What are some ways to direct users from one page to another without relying on server-side programming?

Is there a way to create a redirect page using jQuery or JavaScript? What is the process of writing client-side scripting code to redirect the browser from one page (page1) to another page (page n)? ...

How to add and append values to an array in a Realtime Database

My React.js app allows users to upload songs to Firebase and view the queue of uploaded songs in order. The queue can be sorted using a drag-and-drop system that updates the database in Firebase. Is there a way to insert these songs into an array when uplo ...

"The 'BillInvoice' object must be assigned a primary key value before it is ready for this relationship" - Error Message

There is an issue in my Django project related to the creation of a BillInvoice and its associated BillLineItem instances. The error message I'm receiving states: "'BillInvoice' instance needs to have a primary key value before this re ...

The time-out counter fails to detect the input field

After writing a method to reset the timeout on mouse click, keyup, and keypress events, I realized that it does not account for input fields. This means that when I am actively typing in a field, the timeout will still occur. Below is the code snippet: ...

Transferring client-side data through server functions in Next.js version 14

I am working on a sample Next.js application that includes a form for submitting usernames to the server using server actions. In addition to the username, I also need to send the timestamp of the form submission. To achieve this, I set up a hidden input f ...

Exploring an alternative perspective on successful login in angular.js

Today was the beginning of my project to convert a website to angular.js. The main page is served by index.html and includes ng-view for other views such as login and signup. Working closely with a backend developer, I have successfully integrated a rest c ...

Incorporating additional options onto the menu

I recently designed a menu on https://codepen.io/ettrics/pen/ZYqKGb with 5 unique menu titles. However, I now have the need to add a sixth title to the menu. After attempting to do so by adding "strip6" in my CSS, the menu ended up malfunctioning and looki ...

Issue with Material UI dropdown not selecting value on Enter key press

I have encountered an issue with the material UI dropdown component that I am using. When I navigate through the dropdown options using arrow keys and press enter, the selected value does not get highlighted. Below is the code snippet for the dropdown: ...

Utilize Node.js to proxy Angular requests to a service hosted on Azurewebsites

I am trying to set up a proxy post request in my Node.js server and receive a response from the target of this request. Below is an excerpt from my server.js file code where I have implemented the proxy, but I am facing a issue with not receiving any respo ...

ng-repeat to prevent duplicate items from displaying

I intentionally have duplicates in my array of items and I am looking for a way to hide just one of them when clicked within my ng-repeat. Is there a way to hide only one of the duplicated items on click? I feel like I might be overlooking something, as ...

How to stop vuetify checkbox from auto-checking?

I need the v-checkbox to stay unchecked even after typing in the text field. Current Issue: The checkbox automatically checks itself when I click outside the box or enter text in the text field below. Expected Behavior: The checkbox should remain unche ...

What is the process of linking this JavaScript code to an outer stylesheet and integrating it with the HTML document?

After encrypting an email address using Hiveware Enkoder, the result can be found below. obfuscated code I typically include it directly inside the div as is. However, I would like to streamline my code by placing it in an external file. While I know ho ...

What is the best way to showcase the chosen items in a dropdown menu?

There seems to be an issue with the selected item not appearing in the input field. export default function BasicSelect() { const [sortBy, setSortBy] = useState(""); const [condition, setCondition] = useState(""); const [delivery, ...

Issue with jQuery incorrectly calculating height post-refresh

I am currently utilizing jQuery to vertically center various elements on a webpage. Due to lack of support in older versions of IE, I cannot use the table-cell CSS statement. Therefore, I am using jQuery to calculate half of the height and then position it ...

Vuex - Issue with module state causing undefined return value

Hey there, I'm a bit puzzled as to why the state property is returning undefined. I am relatively new to vue.js and really need to grasp how this all functions. Here's what I've been working on: In my state.js file for let's say the t ...

Strange behavior detected in TypeScript generic function when using a class as the generic parameter

class Class { } const f0 = <T extends typeof Class> (c:T): T => { return c } const call0 = f0 (Class) //ok const f1 = <T extends typeof Class> (c:T): T => { const a = new c() return a //TS2322: Type 'Class' is not assigna ...

Trying to incorporate a PHP echo statement into the innerHTML of a button is ineffective

I have a piece of jQuery code that is not functioning as expected: $("#erase").click(function(){ $("#erase").attr("disabled", "disabled"); // Prevent double-clicking $(this).html("Erasing..."); $.post("erase.php", {target: $("#targ ...