Wednesday, September 13, 2006

Ruby file upload

Uploading files in Ruby took a little time - I was mainly hung up on the File and Directory management. But, after a little trial and error on my part, here's the result. Comments are welcome, as I'd like to improve it...

Some notes - I wanted to store the images in a custom directory under /resources. The resouce model object has a 'path' and a 'title' property.

def self.new_from_upload (upload, directory)
file_name = upload.original_filename
dir_path = "#{RAILS_ROOT}/public/resources/#{directory}"
file_path = "#{dir_path}/#{file_name}"
resource_path = "/resources/#{directory}/#{file_name}"
file_name.chomp!(" ") # remove spaces on the ends

if file_name.length > 0
data =
# Delete file if it exists

delete_file_if_present file_path

# Write new file
create_dir_if_missing dir_path, "wb") do
f f.write(data)

resource =
resource.title = file_name
resource.path = resource_path
return resource

def self.create_dir_if_missing name
Dir.mkdir(name) unless

def self.delete_file_if_present file_path
File.delete(file_path) unless !File.exists?(file_path)

This creates the directory and the file (if missing). Overwriting the file when it's uploaded again.

One improvement that is coming - I'm going to store the file in a temporary directory until it is uploaded. Once in place - I'll move it over and update the model object.


  1. Anonymous6:42 AM

    Learn the difference between Ruby and Rails.

  2. Anonymous5:09 PM

    why just not use the paperclip plugin? save yourself a lot of time and effort.

  3. Anonymous12:10 PM

    I find your tutorial very useful for my project. Though I'm having problems.

    When I upload the file...
    The file is recognized as a HASH, so I'm not able to use functions like OPEN, WRITE. Even getting the filename was different. I accessed it by accessing a hash.

    How can I make the program be recognized as a "File"

  4. Anonymous9:13 PM

    It's kinda hard reading unindented code, still thanks for this.