Today, the rails version of the picture upload, is the most common upload picture here of the rails versions 2.3.5
first create a new write_pic model content as follows:
Copy Code code as follows:
Class Writepic
Require "Rmagick"
Require "UUID"
def self.write (pic_data,ori_name,resize = Nil,file_type = "jpg", Tag=false)
#File. Delete ("C:/programdata/ruby-uuid") if rails_gem_version = = ' 2.1.2 '
UUID = Ori_name | | "#{uuid.new.generate}.#{file_type}"
i = Magick::image.from_blob (pic_data).
If resize
P=resize[:width].to_i*1.00/i.columns
i.resize! (resize[:width],resize[:height]| | i.rows*p)
End
Wh=0
width = i.columns
Height = i.rows
If width > Height
WH =1
End
I.write ("#{rails_root}/public/images/user_pic/#{uuid}")
If tag
Return Wh,uuid
Else
return UUID
End
End
def self.get_pic (URL)
UUID = "#{uuid.new.generate}.#{file_type}"
IMG_ORIG1 = Magick::image.read (URL).
Image1 = Img_orig1.resize_to_fit (300,300)
Image1.write ("#{rails_root}/public/images/weibo_pic/#{uuid}")
return UUID
End
End
Upload the image is used by the plug-in so the top loaded plug-ins.
Call Write_pic This model file is written as follows
Copy Code code as follows:
Class Theme < ActiveRecord::Base
Require "Rmagick"
Require "UUID"
def _image= (Picture_field)
If Picture_field!= ""
Self.image = Writepic.write (Picture_field.read,self.image,nil)
End
End
def _image
Self.image
End
def suoluetu= (Picture_field)
If Picture_field!= ""
Self.thumbnail = Writepic.write (Picture_field.read,self.thumbnail,nil, "PNG")
End
End
def Suoluetu
Self.thumbnail
End
End
Controller don't care too much, directly on view
Copy Code code as follows:
<% form_for (@theme,:html=>{:multipart=> ' true '}) do |f|%>
<%= f.error_messages%>
<p>
<%= f.label:name%><br/>
<%= F.text_field:name%>
</p>
<p>
<%= F.label:color%><br/>
<%= F.text_field:color%>
</p>
<p>
<%= F.label:lastcolor%><br/>
<%= F.text_field:lastcolor%>
</p>
<p>
<%= f.label:image%><br/>
<%= F.file_field: _image%>
</p>
<p>
<%= f.label:thumbnail%><br/>
<%= F.file_field:suoluetu%>
</p>
<p>
<%= f.submit "Create"%>
</p>
<% End%>
<%= link_to ' Back ', Themes_path%>