Tuesday, January 26, 2010

Ruby on Rails : File Upload

1. Views
<% form_for(@upload, :html => {:multipart => true}) do |f| %>
User id: <br /><%= f.text_field :user_id %>
Select file: <br /><%= f.file_field :filename%>
<%= f.submit 'Create' %>
<% end %>


2. Models
class Upload < ActiveRecord::Base def self.save(data, insert)
# retrieve the filename from the file object
fullname = data['filename'].original_filename

# get only the filename, not the whole path (from IE)
name = File.basename(fullname)

# replace all none alphanumeric, underscore or periods
# with underscore
name.sub(/[^\w\.\-]/,'_')

# store the original filename in the insert object and storing other info
insert.filename = name
insert.content_type = data['filename'].content_type
insert.size = data['filename'].size
insert.stored_filename = (1 + rand(99999999)).to_s << '.' << name # set the storage directory directory = "/tmp/file/uploads"

# write to the file system
path = File.join(directory, insert.filename)
File.open(path, "wb") { |f| f.write(data['filename'].read) }
end

end


3. Controller
def create
@upload = Upload.new(params[:upload])    
post = Upload.save(params[:upload], @upload)

respond_to do |format|
if @upload.save
flash[:notice] = 'File was successfully created.'
format.html { redirect_to(@upload) }
format.xml  { render :xml => @upload, :status => :created, 
:location => @upload}
else
format.html { render :action => "new" }
format.xml  { render :xml => @upload.errors, 
:status => :unprocessable_entity }
end
end
end

def destroy
@upload = Upload.find(params[:id])
# Delete from database
@upload.destroy
# Delete file from directory
File.delete("#{RAILS_ROOT}/tmp/file/uploads/#{@upload.filename}")

respond_to do |format|
format.html { redirect_to(uploads_url) }
format.xml  { head :ok }
end
end


If you find this useful, would you like to buy me a drink? No matter more or less, it will be an encouragement for me to go further. Thanks in advance!! =)

No comments:

Post a Comment