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下写编码识别、编码转换的痛苦。
原文链接: https://www.cnblogs.com/jzlikewei/p/3157940.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/93724
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!