Tuesday, June 29, 2010

How to write to a file in Ruby on Rails

This is a simple and easy way to write to a file in Ruby on Rails.
------------------------------------------------
# The content you are going to write to the file 
your_text = "Hello world... !"
  
directory = "public/files"
file_name = "your file name.txt"
 
# create the file path
path = File.join(directory, file_name)
 
# write the file
File.open(path, "w") { |f| f.write(your_text)  
------------------------------------------------
If you are writing a binary file.. for example a pdf file from a file upload use 'wb' instead of 'w'
------------------------------------------------
file_content # this will be in binary format for a pdf file. 

directory = "public/files"
file_name = "your_pdf_file.pdf"
 
# create the file path
path = File.join(directory, file_name)  
# write the file
File.open(path, "wb") { |f| f.write(file_content)  
------------------------------------------------
Here is a sample view file with a form to upload a file. Remember that you have to set 'multipart' option to true to enable file uploads:
------------------------------------------------
<% form_for(upload, :url => {:action => 'create'}, :html => {:multipart => true}) do |f| %>  
    Document tile
   <%= f.text_field :title %>
  
    Author's first name
    <%= f.text_field :author_first %>
  
    Author's last name
    <%= f.text_field :author_last %>
    
    Nicta email address
    <%= f.text_field :email %>
   
   Upload
    <%= f.file_field :datafile %>
  
    <%= f.submit "Create", 
:onclick => "document.getElementById('black_cover').style.display = 'block';" %>  

<% end %>
------------------------------------------------

Below is the controller 'create' action that gets called upon the form submit. The saveFile method in model is the one that actually does the work. The controller simply passes the uploaded file content (:upload) to the saveFile() funciton in the model
------------------------------------------------
 def create
    upload = params[:upload]
   
    # Model will save the file if it's valid
    success, filename = Upload.saveFile(upload)
   
    if (success)
      post = Upload.new do |u|
        u.title = upload['title']
        u.author_first = upload['first_name']
        u.author_last = upload['last_name']
        u.email = upload['email']
        u.filename = filename
      end
    ... 
    ..
    .
------------------------------------------------
Finally, here is the saveFile() function from the model
------------------------------------------------
def self.saveFile(upload)
    if upload['datafile'] == ""
       return [false,  "Upload failed: No document selected for the upload!"]
    end
    
    name =  upload['datafile'].original_filename || nil
    file_type = upload['datafile'].content_type || nil
    file_size = upload['datafile'].size || nil
    
    if name.nil?
      return [false,  "Upload failed: Invalid document name!"]
    end
    
    # check file-type
    if file_type != 'application/pdf'
      return [false,  "Upload failed: File is not a pdf!"]
    end
    
    # check file-size File.     if file_size < 5000
      return [false, "File size was: #{file_size}. Document has to be at least 5KB"] 
    else if file_size > (20*1000*1000) 
      return [false, "File size was: #{file_size}. Document has to be less than xxMB"]
    end
    end
  
    directory = "public/uploads"
    # create the file path
    path = File.join(directory, name)
    # write the file
    File.open(path, "wb") { |f| f.write(upload['datafile'].read) }
    
    return [true, name]
  end 
------------------------------------------------

That's it.


No comments :

About Me

Popular Posts

Designed By Seo Blogger Templates