`
nnnnon
  • 浏览: 147832 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

rails 上传图片

    博客分类:
  • RORs
阅读更多

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》

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics