Codesnipp.it Social Code Sharing

Sam Gray

Ruby on Rails Upload File Script

by Sam Gray on Oct 01, 2010

#Here is a simple upload file script for Ruby on Rails. #place in a model def self.saveImage(upload) name = upload[:file2].original_filename directory = "/Users/sam/Desktop/imagefolder" # create the file path path = File.join(directory, name) while File.exist?(path) fileExtention = File.extname(name) name = File.basename(name, ".*") name << "o" name << fileExtention path = File.join(directory, name) end # write the file File.open(path, "wb") { |f| f.write(upload[:file2].read) } end #place in a controller def uploadFile User.saveImage(params[:file]) #inplace of "user #put whatever class/model you decided to put the saveImage method #above in redirect_to(:action => "index") end #place in the .html.erb view file you want <%= form_tag({:action => "uploadFile"}, {:multipart => true}) -%> <p><label for="upload_file">Select File</label> <%= file_field(:file, :file2) %></p> <%= submit_tag "Upload" %>

Can't see the comments? Please login first :)