File upload

What Im trying to do is upload an image from a form and save it in
/public/images. For some very strange reason I get this:

undefined method `original_filename’ for “07390005.JPG”:String

Although the form has :multipart => true.

Im gonna post the code here:

This is the view bit:

<%=form_tag({:action => “add_news”}, :multipart => ‘true’)%>

Im posting back to myself.

This is the controller bit:

  if request.get?
            @news = News.new()
    else
            @news = News.new(params[:news])
            @news.save
    end

This is the model:

    def image=(image_field)
            @uploaded_file = image_field
            @filename = 

base_part_of(@uploaded_file.original_filename)
self.image = @filename
end

    def base_part_of(file_name)
            name = File.basename(file_name)
            name.gsub(/[^\w._-]/, '')
    end

I have no idea why this doesnt work.

I’m not sure why it isn’t working. Did you look at your generated HTML
and check that everything looks the way it should? I struggled with
getting uploading files to work for a while and just got it recently. I
don’t know if there’s some disadvantage to doing it this way, but I just
put my file writing code in the controller and pull straight from my
params.

For some reason, even though I have the regex, I was getting one param
each time that didn’t contain a file, so I had to put the next statement
in. Now it works fine, though I should probably include a gsub call as
well.

Jason

params.each { |key, value|
if /file_\d+/.match(key)
next if (!filename =
params[key].original_filename.split(’/’).last)
File.open( filename, “wb”) { |f|
f.write(params[key].read)
}
end
}

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