您的位置:首页 > 编程语言 > PHP开发

ThinkPHP微信开发实例——JSSDK图像接口上传下载并将图片流写入本地

2015-08-21 11:09 459 查看

前端

<div>
<img class="preview" src="{$ig'}" style="width: 250px;"/>
<button class="uploadImage" type="button" id="vt">点击上传</button>
<input id="ig" type="hidden" name="media_id" value="{$ig}">
</div>

<script type="text/javascript" src="/jweixin-1.0.0.js"></script>
<script>
wx.config({
debug: false,
appId: '<?php echo $signPackage["appId"];?>',
timestamp: <?php echo $signPackage["timestamp"];?>,
nonceStr: '{$signPackage["nonceStr"]}',
signature: '{$signPackage["signature"]}',
jsApiList: [
/* 所有要调用的 API 都要加到这个列表中*/
'chooseImage',
'previewImage',
'uploadImage',
'downloadImage'
]
});
wx.ready(function() {
//手机相册选图或拍照
var images = {
localId: [],
serverId: []
};
//上传图片
$(".uploadImage").click(function() {
var that = $(this);
images.localId = [];
wx.chooseImage({
success: function(res) {
images.localId = res.localIds;// 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
if (images.localId.length == 0) {
alert('请先使用 chooseImage 接口选择图片');
return;
}
if (images.localId.length > 1) {
alert('目前仅支持单张图片上传,请重新上传');
images.localId = [];
return;
}
var i = 0,
length = images.localId.length;
images.serverId = [];
function upload() {
wx.uploadImage({
localId: images.localId[i],
success: function(res) {
i++;
var media_id = res.serverId; /*返回图片的服务器端ID,serverId 即 media_id*/                                                                    that.siblings('img.preview').attr('src', images.localId[0]);
that.siblings("input[name='media_id']").val(media_id);//对隐藏域赋值传到后台处理
images.serverId.push(res.serverId);
if (i < length) {//现在只能单张
upload();
}
},
fail: function(res) {
alert(JSON.stringify(res));
}
});
}
upload();
}
});
});
});
</script>

后台

/*
* 获取media_id
*/
public function add(){
if(IS_POST){
$serverId = I('post.media_id');
if(!empty($serverId)){
$data['imgpath'] = $this->doWechatPic( $serverId );
}
}

/*
* 从微信服务器获取图片流
*/
public function doWechatPic($serverId){//media_id=jlJs_iQIOA-TKLuhk4nCdPEdXnJ6paIeToO8vr-WUGvz05-6i5n498EzI232xSxn
$media_id = $serverId;//提交过来的serverId即$media_id
$access_token = $this->access_token;
$pic_url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$media_id}";
$filebody = file_get_contents($pic_url);//通过接口获取图片流
$filename = uniqid().'.jpg';            //定义图片名字及格式
return $this->saveFile($filename, $filebody);
}

/*
* 定义文件路径,写入图片流
*/
public function saveFile($filename, $filecontent){
$upload_dir = "./image/".date("Ymd");//保存路径,以时间作目录分层
$mkpath = $upload_dir;
if(!is_dir($mkpath)){
if(!mkdir($mkpath)){
die('no mkdir power');
}
if(!chmod($mkpath,0755)){//若服务器在阿里云上不建议使用0644
die('no chmod power');
}
}
$savepath = $upload_dir.'/'.$filename;
if(file_put_contents($savepath, $filecontent)){//写入图片流生成图片
return $upload."/".$filename;//返回图片路径
}else{
die('save failed');
}

}


微信官方JSSDK Demo
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: