Skip to content

Instantly share code, notes, and snippets.

@camiloforero
Created November 27, 2019 05:58
Show Gist options
  • Save camiloforero/d5fc1437dd21f5a8bf66dd61600b4011 to your computer and use it in GitHub Desktop.
Save camiloforero/d5fc1437dd21f5a8bf66dd61600b4011 to your computer and use it in GitHub Desktop.
import { DirectUpload } from 'activestorage'; // https://www.npmjs.com/package/@rails/activestorage
createThing = (name, the_attachment) => { // name is a string, the_attachment is a File object
const upload = new DirectUpload(
the_attachment,
'/rails/active_storage/direct_uploads', // This url is exposed by default in your app
);
upload.create((error, blob) => {
if (error) {
// Something happened, handle the error
} else {
// blob.signed_id, a String, is the key piece of data that lets Rails identify the file we are referring to
let signed_id = blob.signed_id;
// BONUS: We can already request the uploaded file from Rails by using this url.
let url = `/rails/active_storage/blobs/${signed_id}/${"whatever_we_want_the_filename_to_be"}`;
let request_body = {
name: name
the_attachment: signed_id
}
post_thing_to_rails(request_body) // This can be REST, or GraphQL, doesn't matter
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment