我正在使用this example for file uploader. 在上傳文件之前,我想打開它,搜索特定單詞,將該單詞分配給數據庫中的某個屬性,將文件保存在數據庫中。Ruby on Rails:在上傳之前搜索文件中的單詞
示例:
我選擇了兩個文件並單擊「上傳」。
文件名被分配給upload_file_name。
文件的大小被分配給upload_file_size。
打開文件,我搜索單詞「Bug」或「Lion」。
如果我找到「Lion」,則應將「Lion」分配給upload_content_type。如果我發現「Bug」,則應將「Bug」分配給upload_content_type。
我不太確定在哪裏定義打開文件的函數:在uploads_controller.rb或uploads.rb?而且我不知道如何爲upload_content_type分配「Bug」。
這是我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
在此先感謝
你做了我的一天。非常感謝 – Tonja
很高興能有幫助:) – nathanvda