breaking into the unknown…

simple file upload in rails

Leave a comment

I have been doing file upload in rails using attachment_fu in initial days and then paperclip since its arrival. But have never used simple file upload i,e without using any gems. Recently I have to redesign the paperclip upload functionality of one of my application(will discuss in some other post), So thought of starting from beginning i,e how simple uploader works, what benefits paperclip or other available gem adds to it etc .

I am assuming you already have some rails 4 application running. We will add photo upload feature to it. This will be our flow.

->There will be a upload button on new photo page.
->User upload a pic using the simple uploaded.
-> On successful upload he will be redirected to show page, displaying the uploaded image.

generate the model and controller with below command on your project root from terminal

$ rails g model Photo pic:attachement
invoke active_record
create db/migrate/20150626122526_create_photos.rb
create app/models/photo.rb

If you see the generated migration file, it has below content

class CreatePhotos < ActiveRecord::Migration
  def change
    create_table :photos do |t|
      t.attachment :pic
      t.timestamps null: false

Run migration to add the photos table

$rake db:migrate

Once the migration is complete and you chek the schema.rb file, you will see below detail of the photos table.

  create_table "photos", force: :cascade do |t|
    t.string   "pic_file_name"
    t.string   "pic_content_type"
    t.integer  "pic_file_size"
    t.datetime "pic_updated_at"
    t.datetime "created_at",       null: false
    t.datetime "updated_at",       null: false

So you can see that t.attachement in the migration file get converted into below 4 fields.

t.string “pic_file_name”
t.string “pic_content_type”
t.integer “pic_file_size”
t.datetime “pic_updated_at”

They represent internal property of any attachement. When user upload any file, you need to read these values from params and need to update these fields. Let generate the controller now

$ rails g controller photos new show create.

It will generate new, show and create action in photos controller and the corresponding views.
It will also generate get routes for all these actions.

  get 'photos/new'
  get 'photos/create'
  get 'photos/show'

remove them and replace with resourceful routes.

resources :photos

write the file upload code to the photos/new.html.erb

<%= form_for @photo, :url => photos_path, :html => { :multipart => true } do |form| %>
  <%= form.file_field :pic %>
  <%=form.submit 'upload'%>
<% end %>

This simply provide a file upload field with a upload button, which submit data to create action.

The whole controller code look as below:

class PhotosController < ApplicationController
  before_action :set_photo, only: [:show]

  def show

  def new
    @photo =

  def create
    @photo =
    @photo_object = params[:photo][:pic]
    @photo.pic_file_name = @photo_object.original_filename
    @photo.pic_content_type = @photo_object.content_type
    respond_to do |format|
        file_name_filesystem = + @photo_object.original_filename
        photo_path_on_filesystem = Rails.root.join('public','uploads', file_name_filesystem),'wb') do |file| 
        format.html { redirect_to @photo, notice: 'Photo was successfully created.' }
        format.json { render :show, status: :created, location: @photo }
        format.html { render :new }
        format.json { render json: @photo.errors, status: :unprocessable_entity }

  def set_photo
    @photo = Photo.find(params[:id])

The points to notice here is the create action. If you put debugger(I use byebug) inside the create action and try to see the params, it look as below

(byebug) pp params[:photo][:pic]
“Content-Disposition: form-data; name=\”photo[pic]\”; filename=\”user1.jpeg\”\r\nContent-Type: image/jpeg\r\n”,

(byebug) pp params[:photo][:pic].content_type

(byebug) pp params[:photo][:pic].original_filename

(byebug) pp params[:photo][:pic].tempfile

(byebug) pp params[:photo][:pic].tempfile.path

So you can see that params[:photo][:pic] is an object in itself from which we can get the name of the file, its content etc.

We have first saved file_name and content_type in db, and then write the files content in public/uploads directory of our project. So that when user visit show page next time we will show him the uploaded image.

NOTE: Instead of writing the content to filesystem, you can send it to any API which handle its storage or do whatever with the data you want to do.

Now in show.html.erb we have below code to render the uploaded photo.

<% pic_path = + @photo.pic_file_name%> 
<%img src="/uploads/<%=pic_path%>" alt="" />

So from above implementation, now we can see what paperclip or other gem add to it:

-> You do not need to handle writing the uplaoded file to filesystem yourself. Gem will take care of it
-> Gem can handle storing the uploaded file on ThirdParty storage like amazone
-> They can provide further processing on image like creating tumbnail, applying affects etc.

Author: arunyadav4u

over 7 years experience in web development with Ruby on Rails.Involved in all stage of development lifecycle : requirement gathering, planing, coding, deployment & Knowledge transfer. I can adept to any situation, mixup very easily with people & can be a great friend.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s