1.所用到的插件
#cdn gem 'carrierwave' gem 'rest-client' gem 'carrierwave-upyun'
2.在config/initializers文件夹下添加carrierwave.rb文件,内容:
CarrierWave.configure do |config| config.storage = :upyun config.upyun_username = "账户名" config.upyun_password = "密码" config.upyun_bucket = "空间名" config.upyun_bucket_domain = "空间访问地址" end
3.新写model: upload.rb
#encoding: utf-8 class Upload BUCKET = "空间名" attr_accessor :save_key, :allow_exts, :content_length_range, :return_url, :notify_url, :unsharp, :quality, :password def initialize( opt ) self.save_key = [opt[:prefix], Time.now.strftime("%y%m%d%I%M%S") +'size'+rand(10000).to_s+ "{.suffix}"].join("/") #文件存放的地址 self.allow_exts = opt[:allow_exts]||"jpg,jpeg,gif,png" #文件类型 self.content_length_range = "0,#{200.kilobyte.to_i}" #大小 self.return_url = opt[:return_url] #回调地址 self.notify_url = opt[:notify_url] #回调地址 self.unsharp = opt[:unsharp]||false self.quality = (opt[:quality] || 95 ).to_i end def expiration Time.now.to_i + 600 end def password "nBD/sdfssdEkDc=" #form_api又拍云外获取的验证密钥 end def policy Base64.strict_encode64( policy_json ) end def policy_json policies = { "bucket" => BUCKET, "expiration" => self.expiration, "save-key" => self.save_key, "return-url" => self.return_url } policies.to_json end def signature Digest::MD5.hexdigest("#{self.policy}&#{self.password}") end end
4.上面的form_api(从又拍云处获取到的验证密匙):
5.help层添加一个方法:
#上传图片所有参数 def upyun_form_input_tag(opts = {}) upload=Upload.new( opts ) return [ tag(:input, :type => :hidden, :name => "policy", :value => upload.policy), tag(:input, :type => :hidden, :name => "signature",:value => upload.signature)].join("\n").html_safe end
6.html文件中写法:
<%=form_tag "http://v0.api.upyun.com/空间名/", :method=>:post, :multipart =>true do%> <%=upyun_form_input_tag( {:prefix=>"/zy_fenxiangs", :notify_url=>upload_picture_index_url} )%> <input type="file" class="btn_up_f" name="file" /> <%=submit_tag "提交"%> <%end%>
7.controller层:
def upload params[:code] #HTTP状态码 params[:message] #返回代码 params[:url] #图片地址 end