Hi,
I''m trying to do some basic file uploads in my form (multiple files). I
only want to store the name of the file in the database and the actual
file in the filesystem. I have made a FileUpload class, since I want to
reuse the code in other forms (don''t really know if this is the way to
go). It works fine when I only submit images, but when I submit a non
image file, I can''t get it to display the error (errors.add(...)), like
when a field is empty. What am I doing wrong (or what are the parts that
are right :D)? Hope somebody can help me out.
Kind regards,
Nick
View (get.rhtml)
----------------
<%= error_messages_for("picture") %>
<%= form_tag({:action => ''save''}, :multipart => true)
%>
Comment: <%= text_field("picture", "comment") %>
<br/>
Upload your picture: <%= file_field("picture",
"picture") %>
<br/>
Upload your picture: <%= file_field("picture",
"picture2") %>
<br/>
<%= submit_tag("Upload file") %>
<%= end_form_tag %>
Controller
----------
def save
@picture = Picture.new(params[:picture])
@file_upload = FileUpload.new()
@picture[:picture] =
@file_upload.files_handler(params[:picture][:picture],"test")
@file_upload1 = FileUpload.new()
@picture[:picture2] =
@file_upload.files_handler(params[:picture][:picture2],"test1")
if @picture.save
redirect_to(:action => ''show'', :id => @picture.id)
else
render(:action => :get)
end
end
Model (file_upload.rb)
----------------------
class FileUpload < ActiveRecord::Base
def initialize
end
def files_handler(bestand,filename)
if bestand.size<=0 && bestand.size<=512000
picture.errors.add(:picture, "Dit is geen geldig bestand.")
end
if bestand.content_type=~/^image/
mime_extensions = {
"image/gif" => "gif",
"image/jpeg" => "jpg",
"image/pjpeg" => "jpg",
"image/x-png" => "png",
"image/jpg" => "jpg",
"image/png" => "png"
}
extensie = mime_extensions[bestand.content_type.chomp]
File.open("#{RAILS_ROOT}/public/pictures/ads/#{filename}.#{extensie}",
"wb") { |f| f.write(bestand.read) }
return "#{filename}.#{extensie}"
else
picture.errors.add(:picture, "Het moet een afbeelding zijn.")
end
end
end
--
Posted via http://www.ruby-forum.com/.