简体   繁体   English

与js上传器集成Rails active_storage

[英]Integration Rails active_storage with js uploaders

有没有人将Rails ActiveStorage与任何js上传器(例如Uppy或Dropzone)集成的示例?

We can do so using "DirectUpload" class of activestorage. 我们可以使用activestorage的“ DirectUpload”类来实现。 It is a javascript class used by activestorage internally to create object of file and direct upload it on specified service. 这是javascript类,activestorage内部使用它来创建文件对象并将其直接上传到指定的服务。

Dropzone required a URL to be specified where it can post the file data while uploading. Dropzone要求指定一个URL,以便在上传时可以在其中发布文件数据。 In that case you can provide temporary URL which is used to provide success message to Dropzone and after that you can create a ActiveStorage DirectUpload object to upload file using Active storage 在这种情况下,您可以提供临时URL,该URL用于向Dropzone提供成功消息,然后,您可以创建ActiveStorage DirectUpload对象以使用Active Storage上传文件

Dropzone.options.folderUpload = {
  maxFiles: 100,
  url: temp_url,
  clickable:false,
  addRemoveLinks: false,
  //timeout: 25000,
  accept: function(file, done) {
  },
  init: function() {
    this.on("success", function(file, response) {
      // window.$('.dz-progress').hide();
      // window$('.dz-size').hide();
      // window.$('.dz-error-mark').hide();
      toastr.success("File uploaded successfully");
    });
  }
}

You can create direct upload file as soon as file is attached using handling file change event and creating object of "DirectUpload" class. 使用处理文件更改事件并创建“ DirectUpload”类的对象,可以在附加文件后立即创建直接上传文件。

Here is brief example 这是简单的例子

import { DirectUpload } from "activestorage"

  // on file selection or change {
  const url = element.dataset.directUploadUrl
  const upload = new DirectUpload(file, url)

  upload.create((error, blob) => {
    if (error) {
      // Handle the error
    } else {
      // Add an appropriately-named hidden input to the form with a value of blob.signed_id
      $('<input>').attr({
        type: 'hidden',
        name: 'your_object[files][]',
        value: blob.signed_id
      }).appendTo('form');
    }
  })
// }

After performing the upload to activestorage you can submit the form using 执行上传到活动存储后,您可以使用

$("form").submit() which will attach those upload to your rails model object. $(“ form”)。submit()会将上传的内容附加到您的rails模型对象上。 Remember you have to update the form with signed id within it else it will not attach the upload to your model object. 请记住,您必须更新其中带有签名ID的表单,否则它将不会将上传内容附加到模型对象。

I have used the above flow recently in one of my project. 我最近在我的一个项目中使用了上述流程。

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

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