Rails API Active Storage, S3 and React JS

Rails API Active Storage, S3 and React JS

Rails API and React JS apps both are in trend. Rails 5.2 come up with many new features and Active storage is one of them. I am not going in detail like what is Active Storage and React JS.
There are some npm that you can use in your react app for file upload like react-activestorage-provider (https://github.com/cbothner/react-activestorage-provider). But,I personally don't like the way to use plugins for every small thing. Here I going to show how you can upload images with in 2 minutes from your react app without any third party plugin.

1) Upload image from React app to Rails.
2) Override active storage method for image preview URL.


1) Upload image from React app to Rails.
When we look at Rails documentation, they provide some JS code sample with DirectUpload NPM package. DirectUpload documentation describe how we can upload image though JS frameworks but given documentation is not suits to React JS. So I tried to find easy and quick way to upload images through React Js.

In first step we will write one method that will use to upload an image. You need to install ActiveStorage NPM before doing this.


I am using Redux and In my code I am calling this method like.

cover_img is my attached name and in rails code its defines in model like has_one_attached :cover_img . You just need to save signed_id in that and image will automatically associate.

2) Override active storage method for image preview URL.
After uploading image if we check request response we didn't find any URL for image preview. So we have override direct_uploads_controller.rb.

Now your upload response will be like

Here service_url will be your image url and rest keys used for S3 upload.


Hope it will work for you :) . If you have any query feel free to leave a comment.