<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: rubyonrails code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sun, 27 Jul 2008 02:48:57 GMT</pubDate>
    <description>DZone Snippets: rubyonrails code</description>
    <item>
      <title>Home-brewed file upload in Ruby on Rails</title>
      <link>http://snippets.dzone.com/posts/show/1805</link>
      <description>Most of this comes from others' work, but I was able to tool it to my needs and fix some bugs.  All of these lines go in the model, which for me has a :file and :content_type attributes.  :file stores the complete path to the uploaded file.  Be sure to change the string in path_to_file to the place where you want files stored, and that proper permissions are set on that path.  Also, sanitize_filename doesn't HAVE to be a private method -- make it public if you want.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;### Model ###&lt;br /&gt; def file=(uploaded_file)  &lt;br /&gt;    @uploaded_file = uploaded_file&lt;br /&gt;    @filename = sanitize_filename(@uploaded_file.original_filename)&lt;br /&gt;    write_attribute("content_type", @uploaded_file.content_type)&lt;br /&gt;  end&lt;br /&gt;  &lt;br /&gt;  def after_create&lt;br /&gt;    if !File.exists?(File.dirname(path_to_file))&lt;br /&gt;      Dir.mkdir(File.dirname(path_to_file))&lt;br /&gt;    end&lt;br /&gt;    if @uploaded_file.instance_of?(Tempfile)&lt;br /&gt;      FileUtils.copy(@uploaded_file.local_path, path_to_file)&lt;br /&gt;    else&lt;br /&gt;      File.open(self.path_to_file, "wb") { |f| f.write(@uploaded_file.read) }&lt;br /&gt;    end&lt;br /&gt;    write_attribute("file", path_to_file)&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  def after_destroy&lt;br /&gt;    if File.exists?(self.file)&lt;br /&gt;      File.delete(self.file)&lt;br /&gt;      Dir.rmdir(File.dirname(self.file))&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;  &lt;br /&gt;  def path_to_file&lt;br /&gt;    File.expand_path("#{RAILS_ROOT}/upload/#{self.id}/#{@filename}")&lt;br /&gt;  end&lt;br /&gt;  &lt;br /&gt;  private&lt;br /&gt;  def sanitize_filename(file_name)&lt;br /&gt;    # get only the filename, not the whole path (from IE)&lt;br /&gt;    just_filename = File.basename(file_name) &lt;br /&gt;    # replace all none alphanumeric, underscore or perioids with underscore&lt;br /&gt;    just_filename.gsub(/[^\w\.\_]/,'_') &lt;br /&gt;  end&lt;br /&gt;  &lt;br /&gt;### View ###&lt;br /&gt;...&lt;br /&gt;&lt;input type="file" name="model[file]" /&gt;&lt;br /&gt;...&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 30 Mar 2006 02:33:29 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/1805</guid>
      <author>seancribbs (Sean Cribbs)</author>
    </item>
  </channel>
</rss>
