Posts tagged: file upload

File upload in ruby on rails.

By , August 30, 2009 4:02 am

There are lots of plugins available for upload files in ruby on rails.

  • file_column plugin:
  • attachment_fu
  • flex_image
  • upload_column
  • and many more

Accoding to  me, all these file are more useful for image uplaoding not other files like voice file, pdf and other.

So I made a defination which check following things and then upload a file on defined location.

1. File extension.

2. Mime type (require mime type plugin)

3. Size of the file

#Define basic things in enviornment/development.rb file

FILE_EXTENSIONS = [".wav",".mp3",".gsm",".pdf"] #Allowed file types

FILE_TEMP_PATH="#{RAILS_ROOT}/public/temp/" #Where file is initialy uploaded

FILE_MIME_EXTENSIONS =["audio/x-wav","audio/mpeg","audio/gsm","audio/x-gsm","application/pdf"] #Allowed file types

FILE_ROOT_PATH= "#{RAILS_ROOT}/public/saved/" #Where file is uploaded permanently

FILE_MAXIMUM_SIZE_FOR_FILE=1048576 #Maximum Size (1MB) define in bytes

#In model

before_save :save_file

attr_accessor :file_data

def get_filename
#define your rename file method
t = Time.now
"file_#{t.strftime("%Y%m%d%H%M")}"
end

def save_file
begin
# No update necessary
return true if self.file_data.blank?
filename = get_filename
return false if filename.nil?

extension = File.extname(self.file_data.original_filename)
if extension.nil?
errors.add(:file_data,"Wrong Extension")
return false
end

# Check if the FILE_TEMP_PATH is created, if not try to create
if !File.directory?(FILE_TEMP_PATH)
File.makedirs(FILE_TEMP_PATH)
end

temp_source = File.join(FILE_TEMP_PATH, filename)
temp_source << extension
final_source = File.join(FILE_ROOT_PATH, filename)
final_source << extension

File.open(temp_source, "wb") { |f| f.write(self.file_data.read)}

size=File.size(temp_source)
extension = File.extname(temp_source)
mime_extension=File.mime_type?(temp_source)
if FILE_MIME_EXTENSIONS.include?(mime_extension) == false
logger.error("Trying to upload file with mime-type: #{mime_extension} ")
errors.add(:file_data,"Only wav, mp3,gsm and pdf files are allowed")
return false
end
if FILE_EXTENSIONS.include?(extension) == false
logger.error("Trying to upload file with extension: #{extension} ")
errors.add(:file_data,"File extension should be wav, mp3, gsm or pdf")
return false
end
if size > FILE_MAXIMUM_SIZE_FOR_FILE
logger.error("Trying to upload file with size: #{size} ")
errors.add(:file_data,"File should not be more than #{FILE_MAXIMUM_SIZE_FOR_FILE} bytes")
return false
end
if valid? #Upload in permanent folder
logger.error("#{self.errors.to_xml}")
self.file=filename
FileUtils.copy_file(temp_source,final_source)
FileUtils.rm(temp_source) if File.exists?(temp_source)
return true
else
errors.add(:file_data,"Invalid file format")
FileUtils.rm(temp_source) #Remove temp file
return false
end
rescue => e
logger.error(e)
errors.add(:file_data,"Invalid file format")
return false
end

end

# In View form

<% form_for :o bj_name,:html=>{:multipart=>true} do |f| %>

<%= f.error_messages %>

File: <%=f.file_field :file_data%>
<%= f.submit "Create" %>

<% end %>

Let me know if you are facing any problem in this..

File upload without reload the page

By , June 1, 2009 12:15 am

It is impossible to upload a file using AJAX but we can upload a file without reload whole page.

How it is possible? Answer is using frame .

We need to use target elemet in form tag. By using target element we submittted form into that frame name of target.

<form target="test_frame" action="/test/upload" id="test_form" method="post" enctype="multipart/form-data">
   <input type="file" name="file" /><br />
   <input type="submit" />
</form>
<iframe id="test_frame" name="test_frame" style="display: none"></iframe>

Now when you click on submit button, data will submitted to hidden frame and action will called and result will displayed into that frame.
So we will return the result to the parent window by using respond_to_parent.
You need to download this plugin from: Here
Implement below code in your controller

class TestController < ActionController::Base
  def upload
    # Do stuff with params[:file]
    responds_to_parent do
      render :update do |page|
        page.replace_html 'test_form', :partial => 'test_form'
      end
    end
  end
end

Panorama Theme by Themocracy