<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: upload code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Fri, 25 Jul 2008 06:37:48 GMT</pubDate>
    <description>DZone Snippets: upload code</description>
    <item>
      <title>Upload a file using Ajax</title>
      <link>http://snippets.dzone.com/posts/show/5166</link>
      <description>This code is categorised as Ajax because it "fits within my definition of Ajax" as explained from the &lt;a href="http://www.openjs.com/articles/ajax/ajax_file_upload/"&gt;Ajax File Upload&lt;/a&gt; [openjs.com] article.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"&lt;br /&gt;  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;&lt;br /&gt;&lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt;&lt;br /&gt;  &lt;head&gt;&lt;br /&gt;    &lt;title&gt;File upload&lt;/title&gt;&lt;br /&gt;    &lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8"/&gt;&lt;br /&gt;    &lt;script type="text/javascript"&gt;&lt;br /&gt;    //&lt;![CDATA[&lt;br /&gt;      function init() {&lt;br /&gt;	document.getElementById('file_upload_form').onsubmit=function() {&lt;br /&gt;                                  //'upload_target' is the name of the iframe&lt;br /&gt;	  document.getElementById('file_upload_form').target = 'upload_target'; &lt;br /&gt;	  }&lt;br /&gt;  }&lt;br /&gt;  window.onload=init;&lt;br /&gt;    //]]&gt;&lt;br /&gt;    &lt;/script&gt;&lt;br /&gt;  &lt;/head&gt;&lt;br /&gt;  &lt;body&gt;&lt;br /&gt;    &lt;form id="file_upload_form" method="post" enctype="multipart/form-data" action="/p/file_upload.cgi"&gt;&lt;br /&gt;    &lt;input name="myfile" id="myfile" size="27" type="file" /&gt;&lt;br /&gt;&lt;br /&gt;    &lt;input type="submit" name="action" value="Upload" /&gt;&lt;br /&gt;&lt;br /&gt;    &lt;iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"&gt;&lt;/iframe&gt;&lt;br /&gt;    &lt;/form&gt;&lt;br /&gt;  &lt;/body&gt;&lt;br /&gt;&lt;/html&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Sat, 23 Feb 2008 14:33:52 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5166</guid>
      <author>jrobertson (James Robertson)</author>
    </item>
    <item>
      <title>Upload a file using Ruby</title>
      <link>http://snippets.dzone.com/posts/show/5165</link>
      <description>The following code was used to upload an image file to the web server. Source code origin: &lt;a href="http://www.zytrax.com/tech/lang/ruby/#upload"&gt;Ruby Language Stuff | mod_ruby File upload scripts&lt;/a&gt; [zytrax.com]&lt;br /&gt;&lt;br /&gt;file: file_upload.cgi&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#!/usr/bin/ruby&lt;br /&gt;&lt;br /&gt;# ruby script fragment&lt;br /&gt;require 'cgi'&lt;br /&gt;require 'stringio'&lt;br /&gt;&lt;br /&gt;cgi = CGI.new()  # New CGI object&lt;br /&gt;puts "Content-Type: text/plain"&lt;br /&gt;puts&lt;br /&gt;print '&lt;result&gt;'&lt;br /&gt;&lt;br /&gt;# get uri of tx'd file (in tmp normally)&lt;br /&gt;tmpfile = cgi.params['myfile'].first.path&lt;br /&gt;&lt;br /&gt;# OR (functionally the same)&lt;br /&gt;tmpfile = cgi.params['myfile'][0].path&lt;br /&gt;&lt;br /&gt;# create a Tempfile reference&lt;br /&gt;fromfile = cgi.params['myfile'].first&lt;br /&gt;&lt;br /&gt;#displays the original file name as supplied in the form&lt;br /&gt;puts fromfile.original_filename&lt;br /&gt;&lt;br /&gt;# displays the content (mime) type e.g. text/html&lt;br /&gt;puts fromfile.content_type&lt;br /&gt;&lt;br /&gt;# create output file reference as original filename in our chosen directory&lt;br /&gt;tofile = '/var/www/yourdomain.com/htdocs/r/'+fromfile.original_filename&lt;br /&gt;&lt;br /&gt;# copy the file&lt;br /&gt;# note the untaint prevents a security error&lt;br /&gt;# cgi sets up an StringIO object if file &lt; 10240&lt;br /&gt;# or a Tempfile object following works for both&lt;br /&gt;File.open(tofile.untaint, 'w') { |file| file &lt;&lt; fromfile.read}&lt;br /&gt;# when the page finishes the Tempfile/StringIO!) thing is deleted automatically&lt;br /&gt;&lt;br /&gt;print '&lt;/result&gt;'&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;file: file_upload.html&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"&lt;br /&gt;  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;&lt;br /&gt;&lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt;&lt;br /&gt;  &lt;head&gt;&lt;br /&gt;    &lt;title&gt;File upload&lt;/title&gt;&lt;br /&gt;    &lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8"/&gt;&lt;br /&gt;  &lt;/head&gt;&lt;br /&gt;  &lt;body&gt;&lt;br /&gt;    &lt;form name='fileupload' enctype="multipart/form-data" &lt;br /&gt;    action='/p/file_upload.cgi' method='post'&gt;&lt;br /&gt;    &lt;input type='file' name='myfile' size="40" /&gt;&lt;br /&gt;    &lt;input type='submit' value"Send it"/&gt;&lt;br /&gt;    &lt;/form&gt;&lt;br /&gt;  &lt;/body&gt;&lt;br /&gt;&lt;/html&gt;&lt;br /&gt;  &lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Sat, 23 Feb 2008 13:26:00 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5165</guid>
      <author>jrobertson (James Robertson)</author>
    </item>
    <item>
      <title>FTPS upload a file from Ruby using Curl command line</title>
      <link>http://snippets.dzone.com/posts/show/4801</link>
      <description>Yes, this is lame, but I didn't have much luck with Ruby libraries, so this is what I came up with.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;`curl -k --ftp-ssl -3 -T#{path} -u#{FTP_USER}:#{FTP_PASS} #{FTP_HOST}`&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;-k forces the connection even if the cert looks bad&lt;br /&gt;-3 turns on SSLv3&lt;br /&gt;-T file to upload&lt;br /&gt;-u user:password</description>
      <pubDate>Tue, 20 Nov 2007 15:46:06 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4801</guid>
      <author>timmorgan (Tim Morgan)</author>
    </item>
    <item>
      <title>upload_to_s3 - Ruby S3 upload client</title>
      <link>http://snippets.dzone.com/posts/show/4088</link>
      <description>Prerequisites:&lt;br /&gt;gem install aws-s3&lt;br /&gt;gem install main&lt;br /&gt;&lt;br /&gt;&lt;code&gt;#!/bin/env ruby&lt;br /&gt;&lt;br /&gt;require 'rubygems'&lt;br /&gt;require 'main'&lt;br /&gt;require 'aws/s3'&lt;br /&gt;include AWS::S3&lt;br /&gt;&lt;br /&gt;Main {&lt;br /&gt;  argument('source_filename') {&lt;br /&gt;    cast :string&lt;br /&gt;    description 'source filename to copy to S3'&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  argument('bucket_name') {&lt;br /&gt;    cast :string&lt;br /&gt;    description 'bucket to place the file in on S3'&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  option('access_key_id') {&lt;br /&gt;    argument :optional&lt;br /&gt;    description 'specify the access_key_id manually'&lt;br /&gt;    default 'put your access key here if you want'&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  option('secret_access_key') {&lt;br /&gt;    argument :optional&lt;br /&gt;    description 'specify the secret key manually'&lt;br /&gt;    default 'put your secret key here if you want'&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  def run&lt;br /&gt;    bucket_name = params['bucket_name'].value&lt;br /&gt;    source_filename = params['source_filename'].value&lt;br /&gt;&lt;br /&gt;    Base.establish_connection!(&lt;br /&gt;      :access_key_id     =&gt; params['access_key_id'].value,&lt;br /&gt;      :secret_access_key =&gt; params['secret_access_key'].value&lt;br /&gt;    )&lt;br /&gt;&lt;br /&gt;    begin&lt;br /&gt;      Bucket.find(bucket_name)&lt;br /&gt;    rescue&lt;br /&gt;      puts "Need to make bucket #{bucket_name}.."&lt;br /&gt;      Bucket.create(bucket_name)&lt;br /&gt;&lt;br /&gt;      # Confirm its existence..&lt;br /&gt;      Bucket.find(bucket_name)&lt;br /&gt;    end&lt;br /&gt;&lt;br /&gt;    puts "Got bucket.."&lt;br /&gt;    puts "Uploading #{File.basename(source_filename)}.."&lt;br /&gt;    S3Object.store(File.basename(source_filename), open(source_filename), bucket_name)&lt;br /&gt;    puts "Stored!"&lt;br /&gt;&lt;br /&gt;    exit_success!&lt;br /&gt;  end&lt;br /&gt;}&lt;/code&gt;</description>
      <pubDate>Fri, 01 Jun 2007 17:21:39 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4088</guid>
      <author>peter (Peter Cooperx)</author>
    </item>
    <item>
      <title>Make a remote URL work like a file upload (in Rails)</title>
      <link>http://snippets.dzone.com/posts/show/3994</link>
      <description>Want to load a remote URL into an acts_as_attachment/attachment_fu model?  Use this little utility class.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;  class UrlUpload&lt;br /&gt;    EXTENSIONS = {&lt;br /&gt;      "image/jpeg" =&gt; ["jpg", "jpeg", "jpe"],&lt;br /&gt;      "image/gif" =&gt; ["gif"],&lt;br /&gt;      "image/png" =&gt; ["png"]&lt;br /&gt;    }&lt;br /&gt;    attr_reader :original_filename, :attachment_data&lt;br /&gt;    def initialize(url)&lt;br /&gt;      @attachment_data = open(url)&lt;br /&gt;      @original_filename = determine_filename&lt;br /&gt;    end&lt;br /&gt;&lt;br /&gt;    # Pass things like size, content_type, path on to the downloaded file&lt;br /&gt;    def method_missing(symbol, *args)&lt;br /&gt;      if self.attachment_data.respond_to? symbol&lt;br /&gt;        self.attachment_data.send symbol, *args&lt;br /&gt;      else&lt;br /&gt;        super&lt;br /&gt;      end&lt;br /&gt;    end&lt;br /&gt;    &lt;br /&gt;    private&lt;br /&gt;      def determine_filename&lt;br /&gt;        # Grab the path - even though it could be a script and not an actual file&lt;br /&gt;        path = self.attachment_data.base_uri.path&lt;br /&gt;        # Get the filename from the path, make it lowercase to handle those&lt;br /&gt;        # crazy Win32 servers with all-caps extensions&lt;br /&gt;        filename = File.basename(path).downcase&lt;br /&gt;        # If the file extension doesn't match the content type, add it to the end, changing any existing .'s to _&lt;br /&gt;        filename = [filename.gsub(/\./, "_"), EXTENSIONS[self.content_type].first].join(".") unless EXTENSIONS[self.content_type].any? {|ext| filename.ends_with?("." + ext) }&lt;br /&gt;        # Return the result&lt;br /&gt;        filename&lt;br /&gt;      end&lt;br /&gt;  end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Now when you have the URL you want to load, do something like this:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;@model.uploaded_data = UrlUpload.new(url)&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Or better yet, make a pseudo-accessor on your aaa/attachment_fu model so you can stay "model-heavy".&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;def url=(value)&lt;br /&gt;  self.uploaded_data = UrlUpload.new(value)&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Fri, 11 May 2007 18:04:51 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3994</guid>
      <author>seancribbs (Sean Cribbs)</author>
    </item>
    <item>
      <title>Very simple php file upload</title>
      <link>http://snippets.dzone.com/posts/show/3729</link>
      <description>I think this is the minimum necessary to upload a file in php. First, the form, index.php:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&lt;form enctype="multipart/form-data" action="upload.php" method="POST"&gt;&lt;br /&gt;    &lt;input type="hidden" name="MAX_FILE_SIZE" value="512000" /&gt;&lt;br /&gt;    Send this file: &lt;input name="userfile" type="file" /&gt;&lt;br /&gt;    &lt;input type="submit" value="Send File" /&gt;&lt;br /&gt;&lt;/form&gt;&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Next, the php to accept the file, upload.php&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&lt;?php&lt;br /&gt;&lt;br /&gt;$uploaddir = '/var/www/uploads/';&lt;br /&gt;$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);&lt;br /&gt;&lt;br /&gt;echo "&lt;p&gt;";&lt;br /&gt;&lt;br /&gt;if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {&lt;br /&gt;  echo "File is valid, and was successfully uploaded.\n";&lt;br /&gt;} else {&lt;br /&gt;   echo "Upload failed";&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;echo "&lt;/p&gt;";&lt;br /&gt;echo '&lt;pre&gt;';&lt;br /&gt;echo 'Here is some more debugging info:';&lt;br /&gt;print_r($_FILES);&lt;br /&gt;print "&lt;/pre&gt;";&lt;br /&gt;&lt;br /&gt;?&gt; &lt;br /&gt;&lt;/code&gt;&lt;br /&gt;</description>
      <pubDate>Mon, 26 Mar 2007 08:00:34 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3729</guid>
      <author>mikewilsonuk (Mike Wilson)</author>
    </item>
    <item>
      <title>Getting the _session_id from SWFUpload (Flash 8 multiple file uploader)</title>
      <link>http://snippets.dzone.com/posts/show/3118</link>
      <description>It appears that Ruby's CGI::Session class will not use the _session_id in the query string when the Request is a POST.&lt;br /&gt;&lt;br /&gt;Normally, a POST-type request occurs when a form is submitted to the server (e.g. a Rails application).  In this scenario, there is an easy workaround since we can send the _session_id as a hidden field.&lt;br /&gt;&lt;br /&gt;With Flash 8, however, there is no way to add a 'hidden field' to the multi-part form data, thus Rails will fail to recognize the _session_id in the query string portion of our request.&lt;br /&gt;&lt;br /&gt;Here is a hackish work-around:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;# The following code is a work-around for the&lt;br /&gt;# Flash 8 bug that prevents our multiple file uploader&lt;br /&gt;# from sending the _session_id.  Here, we hack the&lt;br /&gt;# Session#initialize method and force the session_id&lt;br /&gt;# to load from the query string via the request uri. &lt;br /&gt;# (Tested on Lighttpd)&lt;br /&gt;&lt;br /&gt;class CGI::Session&lt;br /&gt;  alias original_initialize initialize&lt;br /&gt;  def initialize(request, option = {})&lt;br /&gt;    session_key = option['session_key'] || '_session_id'&lt;br /&gt;    option['session_id'] =&lt;br /&gt;      request.env_table["REQUEST_URI"][0..-1].&lt;br /&gt;      scan(/#{session_key}=(.*?)(&amp;.*?)*$/).&lt;br /&gt;      flatten.first&lt;br /&gt;    original_initialize(request, option)&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Sun, 10 Dec 2006 03:14:32 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3118</guid>
      <author>canadaduane (Duane Johnson)</author>
    </item>
    <item>
      <title>XML attributes to database columns</title>
      <link>http://snippets.dzone.com/posts/show/3013</link>
      <description>I recently needed to update a database with the contents of an XML file under a controlled environment (details at &lt;a href="http://pqmf.com"&gt;Blackrat's Blog&lt;/a&gt;) and came up with this. &lt;br /&gt;&lt;br /&gt;With an XML input file of the following format&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&lt;tags&gt;&lt;br /&gt;  &lt;tag name='test' desc='Test Description' other='Other Item' /&gt;&lt;br /&gt;  &lt;tag name='test2' desc='2nd Test Description' other='Another Item' /&gt;&lt;br /&gt;&lt;/tags&gt;&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;and a database which contains identical columns name,desc,other (or a superset of the tags) you can use the follow snippet to populate it. &lt;br /&gt;&lt;br /&gt;View [import_xml.rhtml]&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&lt;h1&gt;Import XML&lt;/h1&gt;&lt;br /&gt;&lt;br /&gt;&lt;%= form_tag({ :action =&gt; 'import_xml'}, { :multipart =&gt; true }) %&gt;&lt;br /&gt;&lt;%= file_field 'document', 'file' %&gt;&lt;br /&gt;&lt;%= submit_tag 'Import' %&gt;&lt;br /&gt;&lt;%= end_form_tag %&gt;&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Controller [names_controller.rb]&lt;br /&gt;&lt;code&gt;&lt;br /&gt;def import_xml&lt;br /&gt;  require 'rexml/document'&lt;br /&gt;  file=params[:document][:file]&lt;br /&gt;  doc=REXML::Document.new(file.read)&lt;br /&gt;  doc.root.each_element('//tag') do |tag|&lt;br /&gt;    @name = Name.new&lt;br /&gt;    @name.update_attributes(tag.attributes)&lt;br /&gt;  end&lt;br /&gt;  redirect_to :action =&gt; 'list'&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;</description>
      <pubDate>Sat, 18 Nov 2006 04:32:07 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3013</guid>
      <author>blackrat (Paul McKibbin)</author>
    </item>
    <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>
    <item>
      <title>generic file and image models for uploaded files</title>
      <link>http://snippets.dzone.com/posts/show/793</link>
      <description>These are basic models that store a file in a dedicated files table.  Use has_one or has_many to associate this with your actual models.  RMagick is required for images.&lt;br /&gt;&lt;br /&gt;This is my first code dealing with uploads and rmagick, so please comment if you have suggestions.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;class DbFile &lt; ActiveRecord::Base&lt;br /&gt;  IMAGE_TYPES = ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png']&lt;br /&gt;  before_validation     :sanitize_filename&lt;br /&gt;  validates_presence_of :size, :filename, :content_type&lt;br /&gt;&lt;br /&gt;  class &lt;&lt; self&lt;br /&gt;    def new_file(file_data)&lt;br /&gt;      content_type = file_data.content_type.strip&lt;br /&gt;      (IMAGE_TYPES.include?(content_type) ? DbImage : DbFile).new \&lt;br /&gt;        :data         =&gt; file_data.read,&lt;br /&gt;        :filename     =&gt; file_data.original_filename,&lt;br /&gt;        :size         =&gt; file_data.size,&lt;br /&gt;        :content_type =&gt; content_type&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  protected&lt;br /&gt;  def sanitize_filename&lt;br /&gt;      # NOTE: File.basename doesn't work right with Windows paths on Unix&lt;br /&gt;      # get only the filename, not the whole path&lt;br /&gt;      filename.gsub! /^.*(\\|\/)/, ''&lt;br /&gt;&lt;br /&gt;      # Finally, replace all non alphanumeric, underscore or periods with underscore&lt;br /&gt;      filename.gsub! /[^\w\.\-]/, '_'&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;require 'rmagick'&lt;br /&gt;require 'base64'&lt;br /&gt;class DbImage &lt; DbFile&lt;br /&gt;  def data=(file_data)&lt;br /&gt;    with_image(file_data, true) do |img|&lt;br /&gt;      self.width  = img.columns&lt;br /&gt;      self.height = img.rows&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  def with_image(file_data = nil, save_image = false, &amp;block)&lt;br /&gt;    img = Magick::Image::read_inline(Base64.b64encode(file_data || self.data)).first&lt;br /&gt;    block.call(img)&lt;br /&gt;    write_attribute('data', img.to_blob) if save_image&lt;br /&gt;    img = nil&lt;br /&gt;    GC.start&lt;br /&gt;  end&lt;br /&gt;end&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Controller Usage:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;# returns DbImage if content_type matches&lt;br /&gt;db_file = DbFile.new_file(params[:file][:data])&lt;br /&gt;db_file.save&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Model Usage:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;# raw binary image data&lt;br /&gt;File.open('my_file', 'w') { |f| f.write(db_file.data) }&lt;br /&gt;&lt;br /&gt;# Image resizing with rmagick&lt;br /&gt;# automatically creates RMagick::Image and &lt;br /&gt;# invokes GC.start&lt;br /&gt;db_file.with_image do |img|&lt;br /&gt;  img.scale(.25)&lt;br /&gt;  img.write('thumb.jpg')&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Sat, 08 Oct 2005 05:31:43 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/793</guid>
      <author>technoweenie (Rick Olson)</author>
    </item>
  </channel>
</rss>
