微信JSSDK上传图片,代码为上传单张图
Posted 画画520
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微信JSSDK上传图片,代码为上传单张图相关的知识,希望对你有一定的参考价值。
html端
//这里需要注意的是,千万不要把onclick放到input file上
<div class="load_box">
<img src="ajax返回显示的图片,初始化可以设置个默认的URL" alt="" id="img1" class="star" style="height:142px;" onclick="chooseImage(‘file1‘, ‘thumb‘, ‘img1‘)" >
<input type="file" name="fileToUpload" id="file1" style="width: 0px; height:0px;">
//隐藏域为了提交表单,post或get获取图片路径
<input type="hidden" name="thumb" id="thumb" value=""/>
</div>
<div class="load_box">
<img src="ajax返回显示的图片,初始化可以设置个默认的URL" id="img2" style="height:142px;" onclick="chooseImage(‘file2‘, ‘thumb1‘, ‘img2‘)">
<input type="file" name="fileToUpload" id="file2" style="width: 0px; height:0px;">
<input type="hidden" name="thumb1" id="thumb1" />
</div>
JS代码
//引入JSSDK文件
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js" ></script>
<script type="text/javascript" >
//这些配置,php生成
wx.config({
debug: false,
appId: ‘<?php echo $aWechatConfig[‘appId‘] ?>‘,
timestamp: ‘<?php echo $aWechatConfig[‘timestamp‘] ?>‘,
nonceStr: ‘<?php echo $aWechatConfig[‘nonceStr‘] ?>‘,
signature: ‘<?php echo $aWechatConfig[‘signature‘] ?>‘,
jsApiList: [
‘chooseImage‘,
‘uploadImage‘
]
});
//上传图片
function chooseImage(obj, fileid, imgid){
//拍照或从手机相册中选图接口
wx.chooseImage({
count: 1, // 默认9
sizeType: [‘original‘, ‘compressed‘], // 可以指定是原图还是压缩图,默认二者都有[‘original‘, ‘compressed‘]
sourceType: [‘album‘, ‘camera‘], // 可以指定来源是相册还是相机,默认二者都有
success: function(res) {
var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
// alert(‘localIds:‘ + localIds);
//http://blog.csdn.net/turbocc/article/details/61198447
//在选择图片后,采用setTimeout(function(){wx.uploadImage()},100);可以解决android设备下的问题。
setTimeout(function(){
//上传图片接口
wx.uploadImage({
//这块比较坑, localIds.toString(),必须转字符串,或者 ‘‘ + localIds
localId: localIds.toString(), //需要上传的图片的本地ID,由chooseImage接口获得
isShowProgressTips: 1, // 默认为1,显示进度提示
success: function(res) {
var serverId = res.serverId; // 返回图片的服务器端ID, 上传图片有效期3天,可用微信多媒体接口下载图片到自己的服务器,此处获得的 serverId 即 media_id。
// alert(‘serverId:‘ + serverId);
// 调用ajax,走素材解口,保存图片到服务器
var url = ‘/weixin/mobile/ajax.inc.php?action=getwechatmedia‘;
var data = {
mediaId: serverId
};
$.post(url, data, function (result) {
if (result.success) {
$(‘#‘+fileid).val(‘/uploadfile/‘+result.msg);
$("#" + imgid).attr("src" , ‘/uploadfile/‘+result.msg);
} else {
show_warn_pop(result.msg);
}
}, ‘json‘);
},
fail: function (res) {
alert(‘上传失败,请重新上传!‘);
}
})
},100);
},
fail: function (res) {
alert(‘上传失败,请重新上传!‘);
}
});
}
PHP代码
//控制器代码
//引入JSSDK文件,Jssdk.class.php代码见下文。
require_once(‘./model/Jssdk.class.php‘);
$oJssdk = new JSSDK(微信APPID, 微信APPSERCERT);
//这里获取jssdk配置
$aWechatConfig = $oJssdk->getSignPackage();
//这里可以引入模板文件
//表单ajax提交验证代码
//引入JSSDK
require_once(‘./model/Jssdk.class.php‘);
$oJssdk = new JSSDK(WX_MEMBER_FEE_APPID, WX_MEMBER_FEE_APPSERCERT);
//access_token
$sAccessToken = $oJssdk->getAccessToken();
$sMediaId = filter_submit_string($mediaId);
if ( ! $sMediaId) {
return_error_json(‘参数错误,请重新选择图片上传!‘);
}
$sUrl = ‘https://api.weixin.qq.com/cgi-bin/media/get?access_token=‘ . $sAccessToken . ‘&media_id=‘ . $sMediaId;
//文件名称
$sImgPath = date(‘Y‘,time()).‘/‘.date(‘md‘,time()). ‘/‘.time(). ‘.jpg‘;
$sImgName = PHPCMS_ROOT.‘/front/public/uploadfile/‘ .$sImgPath;
$oFileInfo = $oJssdk->downloadWechatFile($sUrl);
if ($oFileInfo[‘body‘]) {
$oJssdk->saveWechatFile($sImgName, $oFileInfo[‘body‘]);
return_success_json($sImgPath);
} else {
return_error_json(‘上传失败,请重新选择!‘);
}
jssdk.class.php
<?php
class JSSDK
{
private $appId;
private $appSecret;
public function __construct($appId, $appSecret)
{
$this->appId = $appId;
$this->appSecret = $appSecret;
}
public function getSignPackage()
{
$jsapiTicket = $this->getJsApiTicket();
// 注意 URL 一定要动态获取,不能 hardcode.
$protocol = (!empty($_SERVER[‘HTTPS‘]) && $_SERVER[‘HTTPS‘] !== ‘off‘ || $_SERVER[‘SERVER_PORT‘] == 443) ? "https://" : "http://";
$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$timestamp = time();
$nonceStr = $this->createNonceStr();
// 这里参数的顺序要按照 key 值 ASCII 码升序排序
$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url";
$signature = sha1($string);
$signPackage = array(
"appId" => $this->appId,
"nonceStr" => $nonceStr,
"timestamp" => $timestamp,
"url" => $url,
"signature" => $signature,
"rawString" => $string
);
return $signPackage;
}
private function createNonceStr($length = 16)
{
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
private function getJsApiTicket()
{
// jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode(file_get_contents("./jsapi_ticket.json"));
if ($data->expire_time < time()) {
$accessToken = $this->getAccessToken();
// 如果是企业号用以下 URL 获取 ticket
// $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
$res = json_decode($this->httpGet($url));
$ticket = $res->ticket;
if ($ticket) {
$data->expire_time = time() + 7000;
$data->jsapi_ticket = $ticket;
$fp = fopen("jsapi_ticket.json", "w");
fwrite($fp, json_encode($data));
fclose($fp);
}
} else {
$ticket = $data->jsapi_ticket;
}
return $ticket;
}
public function getAccessToken()
{
// access_token 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode(file_get_contents("./access_token.json"));
if ($data->expire_time < time()) {
// 如果是企业号用以下URL获取access_token
// $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
$res = json_decode($this->httpGet($url));
$access_token = $res->access_token;
if ($access_token) {
$data->expire_time = time() + 7000;
$data->access_token = $access_token;
$fp = fopen("access_token.json", "w");
fwrite($fp, json_encode($data));
fclose($fp);
}
} else {
$access_token = $data->access_token;
}
return $access_token;
}
//https请求(支持GET和POST)
public function httpGet($url, $data = null)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
//下载文件
public function downloadWechatFile($sUrl)
{
$resourceCh = curl_init($sUrl);
curl_setopt($resourceCh, CURLOPT_HEADER, 0);
curl_setopt($resourceCh, CURLOPT_NOBODY, 0); //只取body头
curl_setopt($resourceCh, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($resourceCh, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($resourceCh, CURLOPT_RETURNTRANSFER, 1);
$package = curl_exec($resourceCh);
$httpinfo = curl_getinfo($resourceCh);
curl_close($resourceCh);
$imageAll = array_merge(array(‘header‘ => $httpinfo), array(‘body‘ => $package));
return $imageAll;
}
//存储文件
public function saveWechatFile($sFileName, $sFileContent)
{
$oLocalFile = fopen($sFileName, ‘w‘);
if (false !== $oLocalFile) {
if (false !== fwrite($oLocalFile, $sFileContent)) {
fclose($oLocalFile);
}
}
}
}
来源:https://my.oschina.net/selly1025/blog/1550725?utm_medium=referral
以上是关于微信JSSDK上传图片,代码为上传单张图的主要内容,如果未能解决你的问题,请参考以下文章