Uploading files in Ruby took a little time - I was mainly hung up on the File and Directory management. But, after a little trial and error on my part, here's the result. Comments are welcome, as I'd like to improve it...
Some notes - I wanted to store the images in a custom directory under /resources. The resouce model object has a 'path' and a 'title' property.
def self.new_from_upload (upload, directory)
file_name = upload.original_filename
dir_path = "#{RAILS_ROOT}/public/resources/#{directory}"
file_path = "#{dir_path}/#{file_name}"
resource_path = "/resources/#{directory}/#{file_name}"
file_name.chomp!(" ") # remove spaces on the ends
if file_name.length > 0
data = upload.read
# Delete file if it exists
delete_file_if_present file_path
# Write new file
create_dir_if_missing dir_path
File.open(file_path, "wb") do
f f.write(data)
end
resource = Resource.new
resource.title = file_name
resource.path = resource_path
return resource
end
end
private
def self.create_dir_if_missing name
Dir.mkdir(name) unless File.directory?(name)
end
def self.delete_file_if_present file_path
File.delete(file_path) unless !File.exists?(file_path)
end
This creates the directory and the file (if missing). Overwriting the file when it's uploaded again.
One improvement that is coming - I'm going to store the file in a temporary directory until it is uploaded. Once in place - I'll move it over and update the model object.
Learn the difference between Ruby and Rails.
ReplyDeletewhy just not use the paperclip plugin? save yourself a lot of time and effort.
ReplyDeleteHi!
ReplyDeleteI find your tutorial very useful for my project. Though I'm having problems.
When I upload the file...
The file is recognized as a HASH, so I'm not able to use functions like OPEN, WRITE. Even getting the filename was different. I accessed it by accessing a hash.
How can I make the program be recognized as a "File"
It's kinda hard reading unindented code, still thanks for this.
ReplyDelete