File Upload in Ruby…so stupidly simple


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

Then in the controller: #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:

Next is the where you chose the directory, “wb” is so Windows doesn’t fumble a binary file:"#{RAILS_ROOT}/public/upload/#{@filename}.csv", "wb") do |f|
#This writes to the opened space above:

Below saves the filename to the db so I can link to the filename later:

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


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: 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