简体   繁体   English

Nuxt 和 cloudinary - 从客户端直接上传图片到 cloudinary

[英]Nuxt and cloudinary - Upload images from client side directly to cloudinary

I want to upload images from my Nuxt (vue) app to Cloudinary directly (no server involved).我想将图像从我的 Nuxt (vue) 应用程序直接上传到 Cloudinary(不涉及服务器)。 I couldn't find any reference to it that acutely do the work?我找不到任何关于它的参考资料来敏锐地完成这项工作?

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

Java script Java 脚本

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

}```

You can see this Cloudinary CodePen example for HTML5 Upload.你可以看到HTML5上传的这个Cloudinary CodePen例子。

the fact you're using Nuxt shouldn't be a problem, since this all happens after rendering anyway.您使用 Nuxt 的事实应该不是问题,因为这一切都是在渲染之后发生的。

Please see this link https://codepen.io/team/Cloudinary/pen/QgpyOK请查看此链接https://codepen.io/team/Cloudinary/pen/QgpyOK

I'm adding the actual code from the codepen我正在添加代码笔中的实际代码

JS 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 ***************** //
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);
}

// *********** 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');

  // Reset the upload progress bar
   document.getElementById('progress').style.width = 0;
  
  // Update progress (can be used to show progress indicator)
  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) {
      // File uploaded successfully
      var response = JSON.parse(xhr.responseText);
      // https://res.cloudinary.com/cloudName/image/upload/v1483481128/public_id.jpg
      var url = response.secure_url;
      // Create a thumbnail of the uploaded image, with 150px width
      var tokens = url.split('/');
      tokens.splice(-2, 0, 'w_150,c_scale');
      var img = new Image(); // HTML5 Constructor
      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]); // call the function to upload the file
  }
};

HTML: 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>

First, install the nuxt cloudinary pachage by visiting this link Nuxt Cloudinary Introduction , then follow the setup documentation and make sure you are setup.首先,通过访问此链接Nuxt Cloudinary Introduction安装 nuxt cloudinary pachage,然后按照安装文档进行操作并确保您已安装。 Next, visit this link Nuxt Cloudinary Upload .接下来,访问此链接Nuxt Cloudinary 上传 That's all.就这样。 Note that the later link uses uploadPreset as object key in the docs.请注意,后面的链接使用 uploadPreset 作为文档中的 object 键。 Please change it to upload_preset so you dont get any error.请将其更改为 upload_preset,这样您就不会收到任何错误。 Post setup code snipet below下面发布设置代码片段

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

      /* Make sure file exists */
      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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM