我将此示例用于文件上传器。 在上传文件之前,我想打开它,搜索一个特定的词,将该词分配给数据库中的一个属性,然后才将文件保存在数据库中。
例子:
我选择两个文件并单击“上传”。
文件名分配给upload_file_name。
文件的大小分配给upload_file_size。
打开文件,我搜索“Bug”或“Lion”一词。
如果我找到“Lion”,则应将“Lion”分配给 upload_content_type。如果我找到“Bug”,则应将“Bug”分配给 upload_content_type。
我不太确定我必须在哪里定义打开文件的函数:在uploads_controller.rb还是在uploads.rb?而且我不知道如何将“Bug”分配给upload_content_type。
那是我的upload.rb:
class Upload < ActiveRecord::Base
attr_accessible :upload, :upload_file_name, :upload_file_size
Paperclip::interpolates :piks do |attachment, style|
attachment.instance.upload_file_name
end
has_attached_file :upload,
:url =>"/system/Files/Files/:piks/:basename.:extension",
:path =>":rails_root/public/system/Files/Files/:piks/:basename.:extension"
include Rails.application.routes.url_helpers
validates :upload_file_name, :presence => true,
:format =>{:with => %r{\.(txt)$}i,:message =>"should have an extension .cell"}
validates_uniqueness_of :upload_file_name, :message =>"exists already."
def to_jq_upload
{
"name" => (read_attribute(:upload_file_name)).split(".").first,
"size" => read_attribute(:upload_file_size),
"url" => upload.url(:original),
"delete_url" => upload_path(self),
"delete_type" => "DELETE"
}
我的 uploads_controller.rb:
def create
p_attr=params[:upload]
p_attr[:upload] = params[:upload][:upload].first if params[:upload][:upload].class == Array
@upload = Upload.new(p_attr)
respond_to do |format|
if @upload.save
format.html {
render :json => [@upload.to_jq_upload].to_json,
:content_type => 'BUUUUU',
:layout => false
}
format.json { render json: [@upload.to_jq_upload].to_json, status: :created, location: @upload }
else
format.html { render action: "new" }
format.json{ render json: {name:(@upload.upload_file_name).split(".").first ,error: @upload.errors.messages[:upload_file_name]}, :status =>422}
end
end
end
数据库:
ActiveRecord::Schema.define(:version => 20120731045929) do
create_table "uploads", :force => true do |t|
t.string "upload_file_name"
t.string "upload_content_type"
t.string "user"
t.integer "upload_file_size"
t.datetime "upload_updated_at"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
end
以及打开文件的功能:
def check
File.open(??filename) do |file|
file.each do |line|
type=/Lion/.match(line)
if type != nil
puts(type[0]) #assign to a database!!
break
end
end
end
end
提前致谢