Forum: Ruby on Rails Re: Re: Uploading files and writing them to server?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A43dfa24838887d5ea9ac1f2820317c4?d=identicon&s=25 Sean Cribbs (Guest)
on 2006-03-29 22:38
(Received via mailing list)
Well maybe 15 lines is a bit of an exaggeration, but it's close.  Most
of this comes from others' work, but I was able to tool it to my needs.
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.  Also, sanitize_filename doesn't HAVE
to be private.

Enjoy!

Sean Cribbs
Web Services - KCKCCC

---------------snip-----------------------
 def file=(uploaded_file)
    @uploaded_file = uploaded_file
    @filename = sanitize_filename(@uploaded_file.original_filename)
    write_attribute("content_type", @uploaded_file.content_type)
  end

  def after_create
    if !File.exists?(File.dirname(path_to_file))
      Dir.mkdir(File.dirname(path_to_file))
    end
    if @uploaded_file.instance_of?(Tempfile)
      FileUtils.copy(@uploaded_file.local_path, path_to_file)
    else
      File.open(self.path_to_file, "wb") { |f|
f.write(@uploaded_file.read) }
    end
    write_attribute("file", path_to_file)
  end

  def after_destroy
    if File.exists?(self.file)
      File.delete(self.file)
      Dir.rmdir(File.dirname(self.file))
    end
  end

  def path_to_file
    File.expand_path("#{RAILS_ROOT}/upload/#{self.id}/#{@filename}")
  end

  private
  def sanitize_filename(file_name)
    # get only the filename, not the whole path (from IE)
    just_filename = File.basename(file_name)
    # replace all none alphanumeric, underscore or perioids with
underscore
    just_filename.gsub(/[^\w\.\_]/,'_')
  end
---------------snip-----------------------


>>> ljw1001@gmail.com 3/29/2006 1:43 PM >>>

if you wouldn't mind that would be great

On 3/29/06, Sean Cribbs <scribbs@kckcc.edu> wrote:On the contrary, I
homebrewed file upload because I had issues with file_column.  I
probably wrote about 15 lines of code, most of them in the model.  I'm
willing to share, if anyone wants the code.

Sean Cribbs
Web Services - KCKCC
This topic is locked and can not be replied to.