Bulk upload in ruby on rails.

A file upload, where we can upload a zip file and it will extract automatically can be done on the following way in Ruby On Rails.

As a first step install the gems, rubyzip and fastercsv.Then Perform the following code :-

<% form_for :file_upload,:url => {:controller=>'bulkupload',:action=>'upload_file'}, :html => { :multipart => true, :target => "frame", :id => "file_upload" } do |f| %>
<input type="file" name="file_upload_product[file_name]"/>
<input type="submit" value="Upload"/>
<%end%>

Now Open up your bulkupload controller and create method upload_file in that

require 'faster_csv'
require 'fileutils'
class BulkuploadProductController < ApplicationController
  def bulk_upload
    begin
     @file=FileUpload.new
     @file.file_name=params[:file_upload_product]['file_name']
     if @file.save
      responds_to_parent do
       render :update do |page|
        page << "$('file_uploaded_id').value="+@file.id.to_s
        page.replace_html 'upload_message',"<span class='heading4'>File has been moved to server. Please click submit to upload.</span>"
       end
      end
     else
      responds_to_parent do
       render :update do |page|
        page.replace_html 'upload_message',"<span class='table_commands_row'>Please Upload File</span>"
       end
      end
     end
     rescue Exception=>e
      puts "ERROR :: bulkupload_products :: upload_file :: #{e.to_s}"
      responds_to_parent do
       render :update do |page|
        page.replace_html 'upload_message',"<span class='table_commands_row'>Some internal Error has occurred</span>"
       end
      end
    end
  end
end
Advertisements