欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

rails上傳圖片代碼實例

 更新時間:2014年06月24日 12:02:52   投稿:junjie  
這篇文章主要介紹了rails上傳圖片代碼實例,包含model層和view層的代碼,需要的朋友可以參考下

今天講解一下rails的圖片上傳,就是最平常的上傳圖片 這里的rails版本2.3.5

首先新建一個write_pic model內(nèi)容如下:

復(fù)制代碼 代碼如下:

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

上傳 圖片是用的插件所以最上面加載了插件。

調(diào)用write_pic 這個model的model文件寫法如下

復(fù)制代碼 代碼如下:

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里面不用在乎太多,直接上view

復(fù)制代碼 代碼如下:

<h1>New theme</h1>
<% 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 %>


 

相關(guān)文章

最新評論