rails 开发随手记 8
2024-08-28 03:04:20
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下写编码识别、编码转换的痛苦。
最新文章
- Codeforces Round #173 (Div. 2)
- 04、AngularJS的ng-bind、多个控制器和apply
- a标签的target指向iframe
- maven工程通过命令打包
- java对redis的基本操作(转)
- dedecms 根据key取得联动类型(enum)值
- System Operations on AWS - Lab 4W - Monitoring (Windows)
- java获取项目地址或tomcat绝对地址
- Qt在表格中加入控件
- ESLint--定制你的代码规则
- spark2.1:rdd.combineByKeyWithClassTag的用法示例
- express应用程序生成器
- hyperscan简单学习(2)
- centos6中iptables单机网络防火墙的使用
- [原]openstack-kilo--issue(十一)Failed connect to 169.254.169.254:80; No route to host
- HDU 5069 Harry And Biological Teacher(AC自动机+线段树)
- http报头 Accept 与 Content-Type 的区别
- Linux命令之乐--read
- Eclipse创建Maven聚合项目
- js,timeout,promise执行顺序
热门文章
- intellij idea 13&;amp;14 插件推荐及高速上手建议 (已更新!)
- FireFox所支持的全部标签(持续更新ing)
- 省赛i题/求1~n内全部数对(x,y),满足最大公约数是质数的对数
- php 设计模式之工厂模式
- [JZOJ 5437] [NOIP2017提高A组集训10.31] Sequence 解题报告 (KMP)
- (二)Ribbon(负载均衡的客户端)+Rest
- mount ntfs 失败解决办法
- Kettle的设计
- xxx while the managed IDbConnection interface was being used: Login failed for user xxx
- 如何设置ASP.NET站点页面运行超时