views:

29

answers:

1

I'm still fairly new to rails but I've done file uploading before. I'm trying to implement very basic file uploading - nothing fancy, just upload the file, save it, and make a record of it. So here's my method for saving the file:

def self.save(upload,name)
    directory='public/uploads'
    ext=File.extname(upload.original_filename)
    path=File.join(directory, "#{name}#{ext}")
    File.open(path,'wb') { |f| f.write(upload.read) }
end

The file is apparently valid, as extname() gets the correct extension. The new file is created at the correct place. But somehow the writing fails, as the file is always empty. Doesn't matter what type of file I use. What could be going wrong? I'm using Rails 3.0 if it matters.

+1  A: 

Try doing File.open(path,'wb') { |f| f.write(upload.read); f.close }

The IO buffer probably isn't flushing, but closing the file should flush it.

Also, I'd strongly recommend using a plugin such as paperclip for file uploads, simply because file uploads can be annoying to manage, and paperclip provides a very nice way to abstract most of that into conventions so you can just add a couple of columns and do model.upload = params[:file].

Jeremy