File Upload in Ruby…so stupidly simple

Rails

On a form:
<%= form_tag({:action=>:save_csv_file}, :multipart => true)%>
<input name="csv_file" type="file">
<%= submit_tag "upload it" %>
<%=end_form_tag%>

Then in the controller:
@name=UserLogs.new #Store the filename in my db
@file=params['csv_file'] # get the file from the form (its called 'csv_file')
if @file.original_filename.index(".csv") #this checks the filename
#in this case its a CSV file

I add a time stamp to the file name:
@filename=@file.original_filename.chomp(".csv")+"_"+Time.now.strftime('%m-%d-%Y_%H_%M_%S')

Next is the where you chose the directory, “wb” is so Windows doesn’t fumble a binary file: File.open("#{RAILS_ROOT}/public/upload/#{@filename}.csv", "wb") do |f|
#This writes to the opened space above:
f.write(params['csv_file'].read)
end

Below saves the filename to the db so I can link to the filename later:
@name.filename=@filename+".csv"
@name.kind="csv_upload"
@name.save

Now you have a user uploaded file stored to the filesystem with its name and type stored in the db.

Advertisements

2 thoughts on “File Upload in Ruby…so stupidly simple

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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