Problem with file_field

Hi,
I trying to do an upload form, bu the file_field doesnt seem to work as
it should. I can’t access the datafile properties…

#form
<% form_for @student,
:url => { :action => “upload_file”,:id=>@student.id }, :multipart =>
true do |f|%>
<%= file_field ‘upload’, ‘datafile’ %>
<%= submit_tag “Upload” %>
<% end%>

#method 1
def upload_file
student = Student.find(params[:id])
student.data_files << DataFile.save(params[:upload])
student.save
redirect_to :edit
end

#Method 2
def self.save(upload)
name = upload[‘datafile’].original_name
puts name
directory = “public/data”
# create the file path
path = File.join(directory, name)
# write the file
File.open(path, “wb”) { |f| f.write(upload[‘datafile’].read) }
self
end

#Error
undefined method `original_name’ for “iPhone intro.pdf”:String

Greg

Try this.
#form
<%form_tag({:action => ‘upload_file’},:id=>@student.id,:multipart =>
true) do-%>
<%= file_field :upload, :datafile%>
<%= submit_tag “Upload” %>
<%end%>

#method
def upload_file
data = params[:upload]
orig_fileName = data[:datafile].original_filename
filePath = “#{RAILS_ROOT}/public/data/#{orig_fileName}”
file_data = data[:datafile].read
File.open(filePath,“wb”){ |f| f.write file_data }
end

Thanks
Senling

On 17 February 2010 05:58, Greg Ma [email protected] wrote:

undefined method `original_name’ for “iPhone intro.pdf”:String

All the clues are there for you in the error.
It’s saying that the upload[:datafile] field is a String object
(you’re expecting a File).
So there’s a problem with your form sending strings instead of files.
The thing that does the magic with turning file_fields from being just
another text input is the multipart value on the form, so that’s
likely to be the problem.
Low and behold - there’s a syntax error in your form definition; it
should be :

<% form_for @student,
:url => { :action => “upload_file”,:id=>@student.id }, :html => {
:multipart =>
true } do |f|%>

(looks like you got a bit crossed between the form_tag and form_for
methods)

That should now at least upload the file to the server, and let you
get on with the rest of the code.

(you’ll save another bug hunt if you change :
upload[‘datafile’].original_name
to
upload[‘datafile’].original_filename
:wink:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs