Hello!
I am using this example for file uploader.
Before uploading a file I would like to open it, search for a specific word, assign this word to an attribute in the database and only then save the file in the database.
Example:
I select two files and click “upload”
The file name is assigned to a upload_file_name. File’s size is assigned to an upload_file_size.
File is opened, I search for a word “Bug” or “Lion”. If i find “Lion”, “Lion” should be assigned to an upload_content_type. If I find “Bug”, “Bug” should be assigned to upload_content_type.
I am not quite sure where I have to define the function that will open a file: in uploads_controller.rb or in uploads.rb? And I do not know how to assign a “Bug” to an upload_content_type.
That is my 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”
}
my 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
Database:
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
And function to open a file:
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
Thanks in advance