How to check if a file exists in Ruby on Rails

Posted on 20 July 2006

Sometimes file uploads can go wrong; rather than risk your Rails app falling over, it makes sense to check if the file actually exists.

Your database might point to a filename in your public folder when there's no file there, to allow for this possibility you can do the following:

FileTest.exists?("#{@document.name}")

In the example above the object 'document' has a file_column field 'name'. Calling @document.name returns an absolute path for the upload.

The FileTest needs to be combined with a check to see if you are expecting a file to exist. So in this case it would be:


if @document.name && FileTest.exists?("#{@document.name}")

The reason for this is because you need to check that the filename is actually in the database before checking the file system.

FileTest is a ruby module that allows you to perform various tests on files, it's well worth checking out.

For my rails projects I've been using the file_column plugin to implement file uploads.

About Paul

Paul works for Kyan web design agency in Surrey, UK as a Ruby on Rails developer.

Follow Paul on Twitter

Email: paulsturgess [at] gmail.com

Read more articles in the archive →

Comments...

  • FileTest.exists? is obsolete use FileTest.exist? (without s).

    Thanks

    Jens at 18 Apr 08 at 07:50

  • Yes, That's I'm looking for. I use this to check image before image_tag

    Thanks.

    JJthai at 05 Feb 09 at 02:53

  • Thanks for this, just what I needed!

    Name: at 11 Aug 09 at 07:04

  • excuse my misunderstanding...do you mean by absoloute path like /public/images/... if I want to point to an image? can you provide an example?

    quote at 03 Jan 10 at 01:59

  • You can use
    if @document.name? && FileTest.exists?("#{RAILS_ROOT}/public/#{@document.name}")

    if @document.name is /sections/subdivisions/image1.jpg" like .. :D

    Shajin at 02 Mar 11 at 04:33

Got something to say?