Skip to content

How To: Secure Upload

cosenmarco edited this page Nov 3, 2011 · 5 revisions

Uploading files to their default directory in the Public folder can be dangerous if you're looking to restrict who can download the file. You will need to avoid uploading files to this Public directory at all cost. Instead, in the root of your folder, you can upload the file and it will by default not be accessible. We will be creating a download in the file controller. This way, you can use authorization (like cancan) to permit access to certain files using download.

Change your document_uploader.rb (uploader file)

def store_dir
  "/PATH/RAILSAPPLICATION/uploads/#{model.id}"
end

def cache_dir
  "/PATH/RAILSAPPLICATION/tmp/uploads/cache/#{model.id}"
end

Make sure that you have write access to those locations. You can then upload your files like normal. However, when you go to recall the file, you will notice that the URL is the full path of that computer where the file is located. This just won't work! In this example, I am uploading a file to

/uploads/fileid/filename.extension

In my routes.rb, I will need to change the path to my file.

  match "/uploads/:id/:basename.:extension", :controller => "redocuments", :action => "download", :conditions => { :method => :get }

In my controller, I will need to create and pass some variables to dynamically change the link.

def download
  path = "/#{redocument.redocument}"
  send_file path, :x_sendfile=>true
end

In my view, I can create my URL link to the file

<%= link_to File.basename(f.redocument.url), "/uploads/#{f.id}/#{File.basename(f.redocument.url)}" %>

Clone this wiki locally