Commit b23ec14b by lanrion

upload media from remote

parent c174eb04
require "rest-client"
require "multi_json"
require "carrierwave"
require "weixin_authorize/carrierwave/weixin_uploader"
require "weixin_authorize/config"
require "weixin_authorize/handler"
require "weixin_authorize/api"
......
# encoding: utf-8
module WeixinAuthorize
module Api
module Media
# 上传多媒体文件
# http请求方式: POST/FORM
# http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE
# 支持传路径或者文件类型
def upload_media(media, media_type)
file = media.is_a?(File) ? media : File.new(media)
def upload_media(media, media_type, remote=false)
file = process_file(media, remote)
upload_media_url = "#{media_base_url}/upload"
http_post(upload_media_url, {media: file}, {type: media_type}, "file")
end
......@@ -24,6 +24,16 @@ module WeixinAuthorize
private
def process_file(media, remote)
if remote
base = WeixinUploader.new
base.download!(media.to_s)
base.file.to_file
else
media.is_a?(File) ? media : File.new(media)
end
end
def media_base_url
"/media"
end
......
......@@ -10,6 +10,11 @@ describe WeixinAuthorize::Api::Media do
File.new(image_path)
end
let(:remote_image_path) do
# "http://l.ruby-china.org/user/large_avatar/273.png"
"http://g.hiphotos.baidu.com/baike/c0%3Dbaike80%2C5%2C5%2C80%2C26/sign=ce55457e4334970a537e187df4a3baad/03087bf40ad162d99455ef4d13dfa9ec8b13632762d0ed14.jpg"
end
it "can upload a image" do
response = $client.upload_media(image_file, "image")
expect(response.code).to eq(WeixinAuthorize::OK_CODE)
......@@ -23,4 +28,10 @@ describe WeixinAuthorize::Api::Media do
expect(response.class).to eq(String)
end
it "can upload a remote image" do
response = $client.upload_media(remote_image_path, "image", true)
expect(response.code).to eq(WeixinAuthorize::OK_CODE)
expect(response.result.keys).to eq(["type", "media_id", "created_at"])
end
end
......@@ -23,6 +23,8 @@ require 'coveralls'
require 'simplecov'
require "codeclimate-test-reporter"
require "pry-rails"
Coveralls.wear!
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment