以前习惯了用webwork,都好久没有过问过文件如何具体上传的了,只是拿cos来用一下,要不是今天需要处理rails文件上传都快忘记了
目标:
将文件保存到指定的文件夹中,对它重命名,保存重命名后的文件名称
为了能使任何controller都能使用文件上传的功能,变将代码放置在application.rb中
# Filters added to this controller will be run for all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
before_filter :configure_charsets
def configure_charsets
@headers["Content-Type"]="text/html;charset=utf-8"
end
def uploadFile(file)
if !file.original_filename.empty?
#生成一个随机的文件名
@filename=getFileName(file.original_filename)
#向dir目录写入文件
File.open("#{RAILS_ROOT}/public/emag/upload/#{@filename}", "wb") do |f|
f.write(file.read)
end
#返回文件名称,保存到数据库中
return @filename
end
end
def getFileName(filename)
if !filename.nil?
require 'uuidtools'
filename.sub(/.*./,UUID.random_create.to_s+'.')
end
end
end
在页面中,我们定义一<%=file_field "object","field"%>
<%=file_field 'book','bgImage'%>
然后在对应的controller中调用即可
def create
if request.get?
@book=Book.new
else
@book=Book.new(params[:book])
@book.bgImage=uploadFile(params[:book]['bgImage'])
if @book.save
redirect_to_index
end
end
end
分享到:
相关推荐
NULL 博文链接:https://dendrobium.iteye.com/blog/305938
NULL 博文链接:https://mylir.iteye.com/blog/800734
可实现多文件的同时上传,控制文件的格式,数量,同时兼容IE6,7,firefox,易于扩展
jquery-fileupload-rails, 用于 Rails的jQuery文件上传集成 Rails 文件上传jQuery-File-Plugin 是一个文件上传插件,由的Tschan 。 jQuery文件上传功能多文件选择。drag&拖放支持。进度栏和jQuery预览图像。 支持...
用于RailsHTML5文件上传器这个gem使用来上传文件。安装在Gemfile中: gem 'rails-uploader'在航线上: mount Uploader :: Engine => '/uploader' 迁移ActiveRecord: $ bundle exec rails g uploader:install用法...
博文链接:https://agi-alvin.iteye.com/blog/77580
NULL 博文链接:https://hlee.iteye.com/blog/360099
css和图片 博文链接:https://hideto.iteye.com/blog/197517
jack_up, 在 Rails 中,[DEPRECATED] 轻松AJAX文件上传 从October年8 月开始,已经不推荐使用 另外,对于其他的, 付费和免费的上传工具,JackUp已经被否决了。 JackUp简单AJAX文件在 Rails 中上传。安装修改你的...
Active Storage 使得在Rails应用中能够很方便上传和引用云服务中的文件,像Amazon S3或Google Cloud Storage,并将这些文件附加到Active Records中。 它还提供用于测试或本地部署的磁盘服务,但重点是云存储。
含有rails的自动完成,上传文件 ,分页,上传文件进度插件
文件上传控件支持多个文件选择,拖放支持,进度条,验证和预览图像,音频和视频的jQuery插件。...支持标准的HTML表单文件上传和任何服务器端平台(谷歌应用程序引擎,PHP,Python和Ruby on Rails的,Java等)。
将文件上传JS库集成到Rails应用程序的Asset管道中。 版 该gem的最新版本捆绑了Dropzone v5.7.1 。 Dropzone 4.x 如果您依赖Dropzone的4.x分支,则需要在Gemfile中指定gem 'dropzonejs-rails', '~> 0.7.4' ,否则...
与支持标准HTML表单文件上传的任何服务器端平台(PHP,Python,Ruby on Rails,Java,Node.js,Go等)一起使用。 演示版 产品特点 多文件上传: 允许一次选择多个文件并同时上传。 拖放支持: 允许通过从桌面或...
rails_kindeditor将帮助您的rails应用程序与kindeditor集成,包括图像和文件上传。 安装及使用 将此添加到您的Gemfile gem 'jquery-rails' gem 'rails_kindeditor' 注意:Rails 5.1已从默认设置中删除了对jQuery...