Rails 實作upload檔案 sample 2

Rails 實作upload檔案 sample 2

多支檔案上傳
view1:
<% form_for :uploadform, :url => { :action => 'upload'}, 
:html => {:multipart => true}  do |f| %>
  <%= f.file_field :datafile %><br />
  <%= f.submit 'Create' %>
<% end %>

view2:
<h1>File Upload</h1>
<%= start_form_tag ({:action => 'uploadFile'}, 
                        :multipart => true) %>
<p><label for="upload_file">Select File</label> : 
<%= file_field 'upload', 'datafile' %></p>
<%= submit_tag "Upload" %>
<%= end_form_tag %>

Controller1:
def upload1
      file_list = params[:attachment]
      file_list.each do |file|
           filename = file.name
           basename = File.basename(filename)
           tempfile = Tempfile.new(basename)
           tempfile.binmode
           tempfile.write file.get_input_stream.read
           s3_obj = bucket.objects[ 'attachments/' + filename ]
           s3_obj.write(tempfile)

    end
end

Controller2:
class UploadController < ApplicationController
  def index
     render :file => 'app\views\upload\uploadfile.rhtml'
  end
  def uploadFile
    post = DataFile.save(params[:upload])
    render :text => "File has been uploaded successfully"
  end
end

Model:
class Datafile < ActiveRecord::Base
   attr_accessor :upload 
   def self.save(upload)
    file_name =  upload['datafile'].original_filename if (upload['datafile'] !='')
 
    file = upload['datafile'].read 

    file_type = file_name.split('.').last
    new_name_file = Time.now.to_i
    name_folder = new_name_file
    new_file_name_with_type = "#{new_name_file}." + file_type
 
    directory = "public/data"
    # create the file path
    path = File.join(directory, file_name)
    # write the file
    File.open(path, "wb") { |f| f.write(upload['datafile'].read) }
  end
end
================================== 
def sanitize_filename(file_name)
  # get only the filename, not the whole path (from IE)
  just_filename = File.basename(file_name) 
  # replace all none alphanumeric, underscore or perioids
  # with underscore
  just_filename.sub(/[^\w\.\-]/,'_') 
end 
==================================
Deleting an existing File:
def cleanup
    File.delete("#{RAILS_ROOT}/dirname/#{@filename}") 
            if File.exist?("#{RAILS_ROOT}/dirname/#{@filename}")
  end

留言

熱門文章