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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With