Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can ActiveStorage be configured to start uploading as soon as the file is attached, as opposed to when the submit button is clicked?

I like the look for the new ActiveStorage module for file uploads in Rails 5.2, but before I go and rewrite a tonne of code for my site, it looks like uploads only start when the user clicks the submit button.

Does anyone know if ActiveStorage can be configured to upload as soon as the file is attached?

like image 871
stephenmurdoch Avatar asked Dec 15 '17 00:12

stephenmurdoch


2 Answers

Yes it is possible 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.

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.

like image 172
Sandeep Garg Avatar answered Nov 07 '22 21:11

Sandeep Garg


I don't think its inbuilt in Active storage. I have not read of any of such feature in Active storage.

Basically, the idea behind the development of Active storage is to provide the inbuilt replacement for carrier wave/paperclip and direct upload on cloud s3/google cloud.

It is possible using some JS. as you can manually submit by create image part as a separate form and submit it using javascript.

like image 28
Rahul Sharma Avatar answered Nov 07 '22 21:11

Rahul Sharma