现在的位置: 首页 > 综合 > 正文

Rails中文件上传

2018年04月19日 ⁄ 综合 ⁄ 共 1447字 ⁄ 字号 评论关闭
以前习惯了用webwork,都好久没有过问过文件如何具体上传的了,只是拿cos来用一下,要不是今天需要处理rails文件上传都快忘记了 

目标: 
  将文件保存到指定的文件夹中,对它重命名,保存重命名后的文件名称 

为了能使任何controller都能使用文件上传的功能,变将代码放置在application.rb中 

Java代码  收藏代码
  1. # Filters added to this controller will be run for all controllers in the application.  
  2. # Likewise, all the methods added will be available for all controllers.  
  3. class ApplicationController < ActionController::Base  
  4.    before_filter :configure_charsets    
  5.   
  6.    def configure_charsets          
  7.        @headers["Content-Type"]="text/html;charset=utf-8"      
  8.    end      
  9.     
  10.   def uploadFile(file)    
  11.      if !file.original_filename.empty?  
  12.        #生成一个随机的文件名      
  13.        @filename=getFileName(file.original_filename)         
  14.        #向dir目录写入文件  
  15.        File.open("#{RAILS_ROOT}/public/emag/upload/#{@filename}""wb"do |f|   
  16.           f.write(file.read)  
  17.        end   
  18.        #返回文件名称,保存到数据库中  
  19.        return @filename  
  20.      end  
  21.   end   
  22.   
  23.   def getFileName(filename)  
  24.      if !filename.nil?  
  25.        require 'uuidtools'  
  26.        filename.sub(/.*./,UUID.random_create.to_s+'.')  
  27.      end  
  28.   end      
  29. end  

在页面中,我们定义一<%=file_field "object","field"%> 

Java代码  收藏代码
  1. <%=file_field 'book','bgImage'%>  

然后在对应的controller中调用即可 

Java代码  收藏代码
  1. def create  
  2.     if request.get?  
  3.       @book=Book.new  
  4.     else  
  5.       @book=Book.new(params[:book])     
  6.       @book.bgImage=uploadFile(params[:book]['bgImage'])   
  7.       if @book.save  
  8.         redirect_to_index  
  9.       end  
  10.     end  
  11.   end  

抱歉!评论已关闭.