rails 开发随手记 8
rails上传文件 无需gem
首先是model
class DataFile < ActiveRecord::Base def initialize end def name @name end def name=(att) @name=att end def save(upload) self.name = upload['datafile'].original_filename+Time.now.to_s directory = "tmp/file" # create the file path path = File.join(directory, self.name) # write the file File.open(path, "wb") { |f| f.write(upload['datafile'].read) } end def delete File.delete(Rails.root.join('tmp','File',name)) end end
接下来是controller:记得要在routes.rb里做好路由分配,save_upload_file要设置成post方式。
def save_upload_file if(params[:upload].nil?) @msg ='请选择一个文件' render "upload_error.js" return end postFile =DataFile.new postFile.save(params[:upload]) render :text => "File has been uploaded successfully" #postFile.delete end def upload end
然后是view,对应的是upload的:
<h1>File Upload</h1> <%= form_tag( save_upload_file_path , :multipart => true,:remote => true) do %> <p><label for="upload_file">Select File</label> : <%= file_field 'upload', 'datafile' ,:id =>"filename"%></p> <%= submit_tag "upload", :class => 'btn btn-primary', :id => 'upload' %> <% end %>
这样就是了。如果需要异步ajax式的又不想用iframe,看着里http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery 不过ie10以下的都不支持罢了。
————————————————————————————————————————————————————————————————————————————
文件读取,编码识别,编码转化
s=File.read("test.csv",:encoding => "gbk")
读进来后就是utf-8的了。
真是太方便了,我还记得当时用c++在windows下写编码识别、编码转换的痛苦。