rails 上传图片


ruby 代码
  1. class CreatePictures < ActiveRecord::Migration  
  2.   def self.up  
  3.     create_table :pictures do |t|  
  4.     t.column :comment:string:limit=>100  
  5.     t.column :name:string:limit=>200  
  6.     t.column :content_type:string:limit=>100  
  7.     t.column :title:binary  
  8.     end  
  9.   end  
  10.   
  11.   def self.down  
  12.     drop_table :pictures  
  13.   end  
  14. end  


ruby 代码
  1. class RenameColumnData < ActiveRecord::Migration  
  2.   def self.up  
  3.   rename_column :pictures,:title:data  
  4.   end  
  5.   
  6.   def self.down  
  7.   rename_column :pictures,:data:title  
  8.   end  
  9. end  

以上是通过migration建立相应的数据表。

 

建立controller:

ruby 代码
  1. class UploadController < ApplicationController  
  2.   def get  
  3.     @picture = Picture.new  
  4.   end  
  5. end  

 

 

建立get template:

ruby 代码
  1. <%= error_messages_for("picture") %>  
  2. <%= form_tag({:action => 'save'}, :multipart => true) %>  
  3. Comment: <%= text_field("picture""comment") %>  

  4.   
  5. Upload your picture: <%= file_field("picture""picture") %>  

  6.   
  7. <%= submit_tag("Upload file") %>  
  8. <%= end_form_tag %>  
  9.   
  10.    

建立model:

ruby 代码
  1. class Picture < ActiveRecord::Base  
  2.   validates_format_of :content_type:with => /^image/,  
  3.     :message => "--- you can only upload pictures"  
  4.   def picture=(picture_field)  
  5.     self.name = base_part_of(picture_field.original_filename)  
  6.     self.content_type = picture_field.content_type.chomp  
  7.     self.data = picture_field.read  
  8.   end  
  9.   def base_part_of(file_name)  
  10.     name = File.basename(file_name)  
  11.     name.gsub(/[^\w._-]/, '')  
  12.   end  
  13. end  

 

扩充controller,添加save action:

ruby 代码
  1. def save  
  2.   @picture = Picture.new(params[:picture])  
  3.   if @picture.save  
  4.   
  5.     redirect_to(:action => 'show', :id => @picture.id)  
  6.   else  
  7.     render(:action => :get)  
  8.   end  
  9. end  

 

扩充controller,添加picture action:

ruby 代码
  1. def picture  
  2.   @picture = Picture.find(params[:id])  
  3.     send_data(@picture.data,  
  4.     :filename => @picture.name,  
  5.     :type => @picture.content_type,  
  6.     :disposition => "inline")  
  7. end  

 

 

定义show action:

ruby 代码
  1. def show  
  2.   @picture = Picture.find(params[:id])  
  3. end  

 

 

 

显示图片:

ruby 代码
  1. <%= @picture.comment %>

      

 

 注:引自Dave Thomas的《Agile Web Development with Rails》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值