rubyはまずサーバーにアップロードして、それからまたクラウドにアップロードします
4357 ワード
1.プラグイン:
#cdn
gem 'carrierwave'
gem 'rest-client'
gem 'carrierwave-upyun'
2.viewレイヤ:
<%=form_tag ajax_up_picture_upload_index_path :method=>:post, :multipart =>true do%>
<input type="file" class="btn_up_f" name="pic_path" />
<%=submit_tag " "%>
<%end%>
3.controllerレイヤ:
#
Upload.upload(params[:pic_path], " ")
4.model層の方法:
#encoding: utf-8
class Upload
require "net/http"
require "uri"
require 'net/http/post/multipart'
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] || "{filename}{.suffix}"
# 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
"ntdsfasdIENDL/SDLDKNDDssddd=" #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
}
policies.to_json
end
def signature
Digest::MD5.hexdigest("#{self.policy}&#{self.password}")
end
#
def self.upload pic_path, relative_path
path, filename = local_upload(pic_path, relative_path)
opt = {}
opt[:prefix] = relative_path + filename
upyun_path = upyun_upload(path, filename, opt)
return upyun_path
end
#
def self.local_upload pic_path, path
name = Time.now.strftime("%y%m%d%I%M%S") + 'size'+ pic_path.size.to_s
suffix=File.extname("#{pic_path.original_filename}")
name<<suffix
directory = UPPATH+path
if !File.exist?(directory)
FileUtils.mkdir_p(directory) #
end
path = File.join(directory, name)
filesave(pic_path, path)
return path, name #
end
#
def self.upyun_upload pic_path, filename, opt={}
file = File.open(pic_path, "rb")
upload=Upload.new(opt)
params={ :policy => upload.policy,
:signature => upload.signature,
:file => UploadIO.new(file, 'application/octet-stream', filename) }
upyun_path=perform_post(URI.parse(UPYUN_BUCKET_DOMAIN), pic_path, params)
return upyun_path
end
private
#
def self.filesave(upload,path)
File.open(path, "wb") { |f| f.write(upload.read) }
end
def self.perform_post uri, pic_path, params
begin
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.request_uri)
req = Net::HTTP::Post::Multipart.new(uri.path, params)
res = JSON.parse(http.request(req).body)
logger.info "----------------upyun ftp picture--------------"
logger.info res
if res["code"]=="200"
return res["url"]
else
return nil
end
rescue
return nil
end
end
end