We’re going to take you through a case where one requires its website visitors to upload an image to the server. It’s quite easy to handle this in a rails application but you will have to create Amazon S3 or Dropbox account for file upload as most of the Rails PaaS providers don’t support file system. Now we will proceed with a simple and small Rails project using App42 File Upload APIs. In App42, the uploaded file goes to CDN network and gives faster access time to your app users, and can be accessed from http endpoint.
To get you started, let’s create a new Rails application called rails_image_upload. It will create a basic structure of the application by using simple rails command.
To know more about integrating rails sdk in your app, please check our previous blog post and App42 Backend.
Our next step will be to create upload controller to handle file upload.
In the below code, we created three methods in the controller. First method: index, will call a view file to display and second function: new, takes file information from the user and passes it to the create method to save image. Let’s add respective code in action.
class UploadController < ApplicationController
@@upload_service = $api.buildUploadService
def index
begin
@upload = @@upload_service.get_all_files
rescue Exception => e
"#{e.message}"
end
end
def new
end
def create
begin
file_type = App42::Upload::UploadFileType.new
upload_file_type = file_type.enum("IMAGE")
upload = @@upload_service.upload_file(params['name'], params['file'].tempfile, upload_file_type, params['description'])
//This will upload your file in APp42 CDN network and gives you http endpoint to access the file.
redirect_to upload_index_path, notice: 'Image uploaded successfully.'
rescue Exception => e
redirect_to upload_index_path, notice: "#{e.message}"
end
end
end
Finally we will create a view file index.html.rb which we have mentioned in controller. Populate this file with the following code:
<% if @upload %>
All uploaded Images
-
<% @upload.fileList.each do |image| %>
- <%= image_tag "#{image.url}", :size => "110x110" %> <% end %>
and below code in views/upload/new.html.rb
Fill image upload details
<%= form_tag(upload_create_path, :multipart => true ) do %>
<%= label_tag(:name, "File name:") %>
<%= text_field_tag :name %>
<%= label_tag(:file, "File Path:") %>
<%= file_field_tag :file %>
<%= label_tag(:description, "Description:") %>
<%= text_field_tag :description %>
<%= submit_tag "submit" %>
<% end %>
<%= link_to "View all Images", upload_index_path %>
You are almost done, Make sure your application root(config/routes.rb) pointing to
"upload#index"
Source Code can be downloaded or viewed from our Git repo. If you have any questions or need any further assistance, please feel free to write us at support@shephertz.com.
Leave A Reply