`
xxj
  • 浏览: 420095 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Rails中文件上传

阅读更多
以前习惯了用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
分享到:
评论
3 楼 hz_qiuyuanxin 2012-12-15  
楼主,正则表达式写错了,是  /.*\./
2 楼 xxj 2007-05-21  
呵呵,这个代码还是老早写的,写的很土:)现在不会这么写的。

ruby支持返回多值的,最简单的例子如:
a,b=b,a
1 楼 xieqibao 2007-05-15  
同时把文件名和文件大小保存到数据库呢??

相关推荐

Global site tag (gtag.js) - Google Analytics