Peter Marklund

Peter Marklund's Home

Tue November 14, 2006
Programming

Rails: File Uploading and Storage

File uploading and storage is no big deal, right? I mean with Ruby it can be as easy as:

  def create
    File.open("/Users/db/_dev/rails/videos/swing.mov", "w") do |f|
      f.write(@params["video"].read)
    end
  end

Don't forget to set :multipart => true on your form though. The easiest (and most naive?) approach to uploading files is probably to use the File Column plugin. The Rails Wiki has a good page that discusses file uploads in more depth. The file system base storage approach that I've used in my Rails app is similar to what's described here. I use the after_save and after_destroy callbacks to create and delete the file in the file system - an approach also described in this Rails manual. Johan Sorensen has some code for doing buffered file uploads that might be useful for huge files.

This page is quite impressive. It has everything you ever wanted to know about the input type="file" form widget, including why browsers will ignore the value attribute if you try to set it. An annoyance is that if the user gets validation errors on a form containing a file_field widget she will have to re-select the file to upload.

The classic controversy is whether to store files in the database or in the filesystem. If you store them in the database you have a more unified and consistent storage solution. You keep all your data in one place, in one format, and the only data you need to back up is your database. On the other hand, putting files in the file system could potentially offload your database and make the database dumps smaller. Also, databases were not really intended to store files, that's what file systems are for. Personally I'm ambivalent on this issue, but due to some incidents with file system storage recently I'm now leaning more in favor of storing files in the database.

Comments

Peter Marklund said over 7 years ago:

Thanks for the tip Jarkko! MogileFS sounds very interesting. It will be interesting to see how it is adopted and I’ll definetely keep it in mind when the need comes up.

--------------------------------------------------------------------------------