Upload images to your Rails API from React the easy way

John Fajardo
Jun 8 · 5 min read
Image for post
Image for post

How do I get started?

rails new your-project --api --database=postgresql
rails active_storage:install
class PostsController < ApplicationController    def index
@posts = Post.all
render json: @posts
end
def create
@Post = Post.create(post_params)
end
private
def post_params
params.permit(:title, :body, :featured_image)
end
end
post "/posts", to: 'posts#create'
get "/posts", to: "posts#index"
config.active_storage.service = :local
rails g model Post title:string body:text
has_one_attached :featured_image
gem 'active_model_serializers'
rails g serializer post
class PostSerializer < ActiveModel::Serializer
attributes :id
end
class PostSerializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers
attributes :id, :title, :body, :featured_image
def featured_image
if object.featured_image.attached?
{
url: rails_blob_url(object.featured_image)
}
end
end
end
state = {
title: '',
body: '',
featured_image: null
}
handleChange = (event) => {
this.setState({ [event.target.name]: event.target.value });
}
<input type="file" accept="image/*" multiple={false} onChange={this.onImageChange} />
onImageChange = event => { 
this.setState({ featured_image: event.target.files[0] });
};
handleSubmit = event => {
event.preventDefault();
const formData = new FormData();
formData.append('title', this.state.title);
formData.append('body', this.state.body);
formData.append('featured_image', this.state.featured_image);
fetch('http://localhost:3000/posts', {
method: 'POST',
body: formData
})
.catch(error=>console.log(error));
{
"id": 1,
"title": "I had a burger",
"body": "And it was awesome!",
"featured_image": {
"url": "http://localhost:3000/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBCZz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--5fe3364316564ccb4dea4a701d248177629b6f74/burger.jpg"
}
<img src={props.post.featured_image.url}>

The Startup

Medium's largest active publication, followed by +684K people. Follow to join our community.

By The Startup

A newsletter that delivers The Startup's most popular stories to your inbox once a month. Take a look

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

John Fajardo

Written by

The Startup

Medium's largest active publication, followed by +684K people. Follow to join our community.

John Fajardo

Written by

The Startup

Medium's largest active publication, followed by +684K people. Follow to join our community.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store