php实现调用微信上传照片然后保存至服务器与数据库
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script type="text/javascript">
wx.config({
//debug: true,
appId: '{{$sites.appid}}',
timestamp: {{$timestamp}},
nonceStr: '{{$noncestr}}',
signature: '{{$signature}}',
jsApiList: [
'chooseImage',//拍照或从手机相册中选图接口
'previewImage',//预览图片接口
'uploadImage',//上传图片接口
'downloadImage', //下载图片接口
]
});
wx.ready(function(){
document.querySelector('#upimg').onclick = function(){
//选择照片
wx.chooseImage({
count: 1, //张数, 默认9
sizeType: ['compressed'], //建议压缩图
sourceType: ['album', 'camera'], // 来源是相册、相机
success: function (res) {
var localIds = res.localIds.toString();
$("#faceImg").attr("src", localIds);//显示图片到页面上
//上传至微信服务器
wx.uploadImage({
localId: localIds, // 需要上传的图片的本地ID,由chooseImage接口获得
success: function (res) {
var serverId = res.serverId; // 返回图片的服务器端ID
$.ajax({
type:"POST",
url:"/api/index.php?type=wechat&m=activitymanage&a=downFile",
data:"serverid="+serverId+"&access_token={{$access_token}}",
dataType:"json",
success:function(msg){
if(msg.status){
$("#picpath").val(msg.filename);
}
}
});
}
});
}
});
};
});
</script>
php代码
/**
* 根据serverId将微信服务器上的图片保存至服务器
*
*/
public function downFile()
{
$this->_globals();
$accessToken = $_POST["access_token"];
$media_id = $_POST["serverid"];
$str = date('YmdHis').random(12).'.jpg';
$targetName = dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))) . '/uploads/'.$str;
$ch = curl_init("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$accessToken}&media_id={$media_id}");
$fp = fopen($targetName, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
$msg["status"] = curl_exec($ch);
$msg["filename"] = $str;
curl_close($ch);
fclose($fp);
echo json_encode($msg);
die();
}