Today I will explain how to upload images in rails, which is the most common way to upload images. The rails version is 2.3.5.
Create a write_pic modelThe content is as follows:
Copy codeThe Code is 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). first
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). first
Image1 = img_orig1.resize_to_fit (300,300)
Image1.write ("# {RAILS_ROOT}/public/images/weibo_pic/# {uuid }")
Return uuid
End
End
Uploading images is a plug-in, so the plug-in is loaded at the top.
Call write_picThe model file of this model is written as follows:
Copy codeThe Code is 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
The controller does not need to care too much, directly go to the view
Copy codeThe Code is as follows:
<H1> New theme <% 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 %>