Rails 實作upload檔案 sample 1


View:
<h1>Upload ZIP with articles</h1>
<% form_tag('upload', :multipart => true) do %>
  <p>
    File:<br />
    <%= file_field_tag 'zip_file' %><br />
  </p>
  <p>
    Country Code:<br />
   <%= text_field_tag 'country_code' %><br />
  </p>
  <p>
    <%= submit_tag "Upload" %>
  </p>
<% end %>
<%= link_to 'Back', pages_path %>


Controller:

def upload
    require 'find'
    require 'fileutils'

    @msg = ""
 
      zipf = params[:upload_file]
      country_code = params[:country_code]
     
      directory = "/tmp/uploads"
      `rm -rf "#{directory}"`    #ruby就是這樣直接執行外部命令。
      `mkdir "#{directory}"`

      path = File.join(directory, zipf.original_filename)
      File.open(path, "wb") { |f| f.write(zipf.read) }

      `unzip "#{path}" -d "#{directory}"`
      `rm #{path}`

      sql_cond = "country_code = '#{country_code}' OR country_code = ''"
      all_tags = WpTag.find(:all, :conditions => sql_cond)
      all_cats = WpCategory.find(:all, :conditions => sql_cond)
      all_sites = WpSite.find(:all,
 :conditions => "country_code = '#{country_code}'")
      cur_sites = all_sites.clone

      Find.find( directory ) do |fpath|
        if FileTest.file?( fpath )

          if cur_sites.empty?
            cur_sites = all_sites.clone
          end

          file_name = File.basename(fpath).chars.gsub(/\.\w+$/, '').gsub(/[_-]/, ' ').capitalize
          content = File.open(fpath).read
          filtered = content.chars.downcase

          tags = self.get_cats_or_tags(all_tags, filtered, 5)
          cats = self.get_cats_or_tags(all_cats, filtered, 2)

          cur_site = cur_sites.delete_at(rand(cur_sites.length))

          article = WpArticle.new(
            :content      => content.chars.tidy_bytes,
            :country_code => country_code,
            :subject      => file_name.chars.tidy_bytes,
            :categories   => cats,
            :tags         => tags,
            :wp_site_id   => cur_site.id)

          article.save
         
          @msg += "Article: <b>#{article.subject}</b> with tags: <b>#{article.tags}</b> and categories: <b>#{article.categories}</b> has been assigned to site: <b>#{cur_site.name}</b><br>"
        end
      end
  

  end

留言

熱門文章