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下写编码识别、编码转换的痛苦。

最新文章

  1. Codeforces Round #173 (Div. 2)
  2. 04、AngularJS的ng-bind、多个控制器和apply
  3. a标签的target指向iframe
  4. maven工程通过命令打包
  5. java对redis的基本操作(转)
  6. dedecms 根据key取得联动类型(enum)值
  7. System Operations on AWS - Lab 4W - Monitoring (Windows)
  8. java获取项目地址或tomcat绝对地址
  9. Qt在表格中加入控件
  10. ESLint--定制你的代码规则
  11. spark2.1:rdd.combineByKeyWithClassTag的用法示例
  12. express应用程序生成器
  13. hyperscan简单学习(2)
  14. centos6中iptables单机网络防火墙的使用
  15. [原]openstack-kilo--issue(十一)Failed connect to 169.254.169.254:80; No route to host
  16. HDU 5069 Harry And Biological Teacher(AC自动机+线段树)
  17. http报头 Accept 与 Content-Type 的区别
  18. Linux命令之乐--read
  19. Eclipse创建Maven聚合项目
  20. js,timeout,promise执行顺序

热门文章

  1. intellij idea 13&amp;amp;14 插件推荐及高速上手建议 (已更新!)
  2. FireFox所支持的全部标签(持续更新ing)
  3. 省赛i题/求1~n内全部数对(x,y),满足最大公约数是质数的对数
  4. php 设计模式之工厂模式
  5. [JZOJ 5437] [NOIP2017提高A组集训10.31] Sequence 解题报告 (KMP)
  6. (二)Ribbon(负载均衡的客户端)+Rest
  7. mount ntfs 失败解决办法
  8. Kettle的设计
  9. xxx while the managed IDbConnection interface was being used: Login failed for user xxx
  10. 如何设置ASP.NET站点页面运行超时