Commit 8f57fa4a by lanrion

can upload any kind picture

parent 9dbd0364
source 'https://rubygems.org'
group :test do
group :test, :development do
gem "rspec", "~> 3.0.0.beta1"
gem "redis-namespace", "~> 1.4.1"
gem "rake", "~> 0.9.6"
gem 'simplecov', '~> 0.7.1', :require => false
gem "codeclimate-test-reporter", require: nil
gem 'coveralls', require: false
end
group :development do
# For debugger
gem "pry-rails", "~> 0.3.2"
......
......@@ -7,8 +7,8 @@ module WeixinAuthorize
# 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, remote=false)
file = process_file(media, remote)
def upload_media(media, media_type)
file = process_file(media)
upload_media_url = "#{media_base_url}/upload"
http_post(upload_media_url, {media: file}, {type: media_type}, "file")
end
......@@ -24,20 +24,67 @@ module WeixinAuthorize
private
def process_file(media, remote)
if remote
base = WeixinUploader.new
base.download!(media.to_s)
base.file.to_file
# CarrierWave.clean_cached_files!
else
media.is_a?(File) ? media : File.new(media)
def process_file(media)
return media if media.is_a?(File) && jpep?(media)
media_url = media
uploader = WeixinUploader.new
if http?(media_url) # remote
uploader.download!(media_url.to_s)
else # local
media_file = media.is_a?(File) ? media : File.new(media_url)
uploader.cache!(media_file)
end
file = process_media(uploader)
# CarrierWave.clean_cached_files!(10)
file
end
def media_base_url
"/media"
end
def process_media(uploader)
uploader = covert(uploader)
uploader.file.to_file
end
# JUST ONLY FOR JPG IMAGE
def covert(uploader)
# image process
unless (uploader.file.content_type =~ /image/).nil?
if !jpep?(uploader.file)
require "mini_magick"
# covert to jpeg
image = MiniMagick::Image.open(uploader.path)
image.format("jpg")
uploader.cache!(File.open(image.path))
image.destroy! # remove /tmp from MinMagick generate
end
end
uploader
end
def http?(uri)
return false if !uri.is_a?(String)
uri = URI.parse(uri)
uri.scheme =~ /^https?$/
end
def jpep?(file)
content_type = if file.respond_to?(:content_type)
file.content_type
else
content_type(file.path)
end
!(content_type =~ /jpeg/).nil?
end
def content_type(media_path)
MIME::Types.type_for(media_path).first.content_type
end
end
end
end
module WeixinAuthorize
class WeixinUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
# 微信只支持jpg格式,目前还有bug.
process :convert => 'jpg'
end
end
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