总体思路
在微信下选好图片后将图片上传到微信服务器,在后端使用微信服务器返回的图片 serverId
加上调用接口的 access_token
通过七牛的 fetch
接口向微信服务器下载多媒体文件的接口请求图片的二进制流,然后保存至自己七牛账号内的特定 bucket
。
调用微信 chooseImage 接口,成功后调用 uploadImage 接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| wx.ready(function () { var images = { localId: [], serverId: [] }; document.querySelector('#chooseImage').onclick = function () { wx.chooseImage({ count:1, success: function (res) { images.localId = res.localIds; $(".weui_uploader_file").show().css('background-image', 'url(' + images.localId[0] + ')');
} }); };
document.querySelector('#uploadImage').onclick = function () { if (images.localId.length == 0) { alert('请先选择图片'); return; }
$.showLoading("请稍等..."); var i = 0, length = images.localId.length; images.serverId = []; function upload() { wx.uploadImage({ localId: images.localId[i], success: function (res) { i++; console.log(res); images.serverId.push(res.serverId);
var url = "<?php echo base_url('vote/home/fetch_url_to_qiniu'); ?>"; $.get(url, {'media_id': res.serverId,'memo': $('.weui_textarea').val()}, function (response) { $.hideLoading(); var data = $.parseJSON(response); if (data.ret == 0) { $.toast(data.msg); window.location.href = "<?php echo base_url('vote/home/vote_list'); ?>"; } else { $.toast("操作失败", "forbidden"); $.noti({ text: data.msg, time: 3000 }); return; } });
if (i < length) { upload(); } }, fail: function (res) { alert(JSON.stringify(res)); } }); }
setTimeout(function () { upload(); }, 1000);
};
wx.error(function (res) { console.log(res.errMsg); }); });
|
在后台使用七牛的 fetch 接口向微信服务器请求文件并存入自己的七牛仓库
下面是七牛PHP fetch接口demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <?php require_once __DIR__ . '/../autoload.php'; use Qiniu\Auth; use Qiniu\Storage\BucketManager; $accessKey = 'Access_Key'; $secretKey = 'Secret_Key'; $auth = new Auth($accessKey, $secretKey); $bmgr = new BucketManager($auth); $url = 'http://php.net/favicon.ico'; $bucket = 'Bucket_Name'; $key = time() . '.ico'; list($ret, $err) = $bmgr->fetch($url, $bucket, $key); echo "=====> fetch $url to bucket: $bucket key: $key\n"; if ($err !== null) { var_dump($err); } else { echo 'Success'; }
|
其中需要特别注意的地方是,通过微信返回的 serverId
去微信服务器下载图片的接口微信公众号
和微信企业号
是不一样的(微信企业号开发文档没有提供媒体下载接口以为是同公众号下载接口一样,结果总是提示 aceess_token
)
微信 JSSDK 说明文档
七牛 fetch 接口说明文档
七牛 PHP-SDK fetch 接口demo