简体   繁体   中英

Integration Rails active_storage with js uploaders

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

We can do so using "DirectUpload" class of activestorage. It is a javascript class used by activestorage internally to create object of file and direct upload it on specified service.

Dropzone required a URL to be specified where it can post the file data while uploading. 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

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.

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. Remember you have to update the form with signed id within it else it will not attach the upload to your model object.

I have used the above flow recently in one of my project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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