media-scientific - IT Blog

the backend developers blog
   

Ruby on Rails Bilder Upload

Es gibt im Grunde zwei Arten, Bilder in eine Ruby on Rails Applikation zu laden.

Die erste geht per Hand:
Im Model werden die folgenden Methoden hinzu gefügt, um ein Bild (oder eine andere Datei) im Filesystem des Servers speichern zu können:



def uploaded_file=(incoming_file)

self.file_name = incoming_file.original_filename

self.content_type = incoming_file.content_type

self.file = incoming_file

end
def file_name=(new_file_name)
write_attribute("file_name", sanitize_filename(new_file_name))
end

def file=(incomming_file)
@temp_file = incomming_file
@filename = incomming_file.original_filename
@content_type = incomming_file.content_type
end
def after_save
if @temp_file
logger.debug("saving '#{RAILS_ROOT}/public/media/#{@filename}'")
File.open("#{RAILS_ROOT}/public/media/#{@filename}", "wb") do |f|
f.write(@temp_file.read)
end
end
end
def after_destroy
File.delete("#{RAILS_ROOT}/public/media/#{@filename}") if File.exist?("#{RAILS_ROOT}/media/#{@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 non-alphanumeric, underscore or periods with underscores
just_filename.gsub(/[^\w\.\-]/,’_')
end

[Quelle: http://manuals.rubyonrails.com/read/chapter/56]

Leave a Reply

You must be logged in to post a comment.