首页 > 学院 > 开发设计 > 正文

rails上传图片代码实例

2019-10-26 19:22:44
字体:
来源:转载
供稿:网友

今天讲解一下rails的图片上传,就是最平常的上传图片 这里的rails版本2.3.5

首先新建一个write_pic model内容如下:
代码如下:
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

上传 图片是用的插件所以最上面加载了插件。

调用write_pic 这个model的model文件写法如下
代码如下:
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
代码如下:
<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 %>

 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表