Search code examples
ruby-on-railsrails-activestorage

Is it possible to use ActiveStorage without a file input?


I haven't seen any documentation on the matter, but to elaborate:

I want to use active storage to upload files in my rails app without having to use a browser's file input element. Whether it be using Drag/Drop, or various custom file pickers, it'd be nice to tell ActiveStorage to upload a file and save it without having to use a file input element.

Also: afaik, it's not allowed to hide a file input and to set it's file contents (as sort of a work around).

Is this possible? Does anyone have an example of how this is done without a file input element?


Solution

  • You can use the DirectUpload class for this purpose. Upon receiving a file from your library of choice, instantiate a DirectUpload and call its create method. create takes a callback to invoke when the upload completes:

    import { DirectUpload } from "activestorage"
    
    // on file selection/drop {
      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
        }
      })
    // }
    

    This class is the rare exception to the rule that undocumented Rails APIs are internal. We just haven’t gotten around to documenting it yet.