Rails之文件上传

在网站public目录下创建upload目录

编写controller如下:文件上传后用它的md5值作为文件名

class TestController < ApplicationController
  def index
  end

  def uploadFile(file)
    if !file.original_filename.empty?
      content=file.read
      @filename=Digest::MD5.hexdigest(content) + "." + file.original_filename.split('.').last.downcase
      File.open("#{Rails.root}/public/upload/#{@filename}", "wb") do |f|
        f.write(content)
      end
      return @filename
    end
  end

  def upload
    unless request.get?
      if filename=uploadFile(params[:file]['file'])
        @pic = filename
      end
    end
  end 
end

上传页面index.html.erb

<h1>Upload File</h1>
<%= form_tag({:action => 'upload'}, :multipart => true) do %>
Upload your file: <%= file_field("file", "file") %>
<br/>
<%= submit_tag("Upload file") %>
<% end %>

显示页面upload.html.erb

<img src="<%= root_url + "upload/" + @pic %>" alt="df" />

 如果基于model用form_for方式创建上传呢表单,代码如下

rails generate scaffold item name:string img_url:string

#item.rb
class Item < ActiveRecord::Base
  attr_accessible :img_url, :name, :load_photo_file
  
  PHOTO_STORE = File.join Rails.root, 'public', 'upload'
  
  after_save :save_photo

   # "f.file_field :load_photo_file" in the view triggers Rails to invoke this method
   # This method only store the information
   # The file saving is done in after_save
   def load_photo_file=(data)
     # Store the data for later use
     @photo_data = data.read
	 self.img_url = Digest::MD5.hexdigest(@photo_data) + "." + data.original_filename.split('.').last.downcase
   end

   # Called when save is completed
   def save_photo
     if @photo_data
       # Write the data out to a file
       name = File.join PHOTO_STORE, self.img_url
       File.open(name, 'wb') do |f|
         f.write(@photo_data)
       end
       @photo_data = nil
     end
   end
end

#_form.html.erb

<%= f.file_field :load_photo_file %>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值