Rails File Upload
File Upload(Save file system)
<%= form_tag([action: :upload_process), multipart: true) do %> <label>File: <%= file_field_tag :upfile, size: 50 %></label> <% end %>
Handle by upload_process
controller
def upload_process
# get file
file = params[:upfile]
# file base name
name = file.original_filename
# permit index
perms = ['.jpg', '.jpeg', '.gif', '.png']
# Check
if !perms.include?(File.extname(name).downcase)
result = 'Can upload only image'
elif file.size > 1.megabyte
result = 'File size should be up to 1MB'
else
File.open('public/docs/#{name}', 'wb') { |f| f.write(file.read) }
result = "Uplod #{name}"
end
render text: result
end
Write file(on disk) using File class
public/docs is rails directory
How to retrieve
params[:upfile] # UploadFile object
UploadFile object
methods
| Method | Description |
|---|---|
| original_filename | |
| content_type | Content type |
| size | |
| read | Read file |
Save into database
class Author < ActiveRecord::Base
validate :file_invalid?
def data=(data) # write data property
self.ctype = data.content_type
self.photo = data.read
end
private
def file_invalid?
ps = ['image/jpeg', 'image/gif', 'image/png']
errors.add(:photo, ' is not image file') if !ps.include?(self.ctype)
errors.add(:photo, ' is over 1MB') if self.photo.length > 1.megabyte
end
end
controller
def updb
@item = Item.find(params[:id])
end
def updb_process
@item = Item.find(params[:id])
if @item.update(params.require(:item).permit(:data))
render text: 'Success'
else
render text: @item.errors.full_messages[0]
end
end
View
<%= form_for(@item, url: {action: updb_process, id: @item }, html:{multipart: true}) do |f| %>
<%= f.label :data, 'File' %>
<%= f.file_field :data %>
<%= f.submit 'Upload' %>
<% end %>
