微信jssdk 上传图片接口官方的是上传到微信服务器怎么上传到自己的服务器

cjfmaster.com 2016-09-20 05:34:42
// 5.3 上传图片
document.querySelector('#uploadImage').onclick = function () {
if (images.localId.length == 0) {
alert('请先使用 chooseImage 接口选择图片');
return;
}
var i = 0, length = images.localId.length;
images.serverId = [];
function upload() {
wx.uploadImage({
localId: images.localId[i],
success: function (res) {
i++;
alert('已上传:' + i + '/' + length);
images.serverId.push(res.serverId);//push() 方法可向数组的末尾添加一个或多个元素
if (i < length) {
upload();
}
},
fail: function (res) {
alert(JSON.stringify(res));
}
});
}
upload();
};


这是微信提供的上传图片的接口,我已经调试好可以上传图片和拍照照片到微信服务器,请问有人知道怎么把图片上传到自己的服务器吗
前端拿到serverId(即media_id)后,将此作为参数去请求后台“获取临时素材接口”
1.//根据微信JS接口上传了图片,会返回上面写的images.serverId(即media_id),填在下面即可  
2. $str = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=''&media_id=''";  
3. //获取微信“获取临时素材”接口返回来的内容(即刚上传的图片)  
4. $a = file_get_contents($str);  
5.//__DIR__指向当前执行的PHP脚本所在的目录  
6. echo __DIR__;  
7. //以读写方式打开一个文件,若没有,则自动创建  
8. $resource = fopen(__DIR__."/1.jpg" , 'w+');  
9. //将图片内容写入上述新建的文件  
10. fwrite($resource, $a);  
11. //关闭资源  
12. fclose($resource);  
这是网上搜集到的但不知怎么用这段代码加在哪里?有大神嘛?多谢指教
...全文
8184 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
画骨难画风 2019-08-09
  • 打赏
  • 举报
回复
大佬没法用啊,有没有完整点的,感谢感谢137213403@qq.com
fictioner 2016-09-21
  • 打赏
  • 举报
回复
前端肯定是要提交的,上传成功后将mediaid赋给隐藏域。附上我的前端和后端代码

<?php include('siteinit.php');?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>东风商用车试用申请</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/animate.min.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/reveal.css">
<style type="text/css">
body{ overflow-y:scroll;}

</style>
</head>

<body style="display:none;">
    <form action="?" method="post" name="form1" id="form1" enctype="multipart/form-data">
<div class="test-page">
<div class="bg"><img src="images/order.jpg" width="100%" alt=""/></div>
	<div class="form-box">
		
    <h3>敬请填写如下信息,开启精彩试用之旅!</h3>
    <div class="text-group">
    	<label for="tname">姓名</label>
        <input type="text" name="tname" id="tname">
    </div>
    <div class="text-group">
    	<label for="mobile">电话</label>
        <input type="tel" name="mobile" id="mobile" onkeyup="value=value.replace(/[^\d]/g,'') ">
    </div>
    <div class="text-group">
    	<a href="#"  data-reveal-id="myModal">
    	<label for="myinfo">自我介绍</label>
        <input type="myinfo" name="myinfo" id="myinfo">
        </a>
    </div>
    <div class="upimg">
    	
 		<a id="chooseImage" class="file" href="#" title="点击添加图片" alt="点击添加图片">
 			
 		</a>
 		<input type="hidden" name="mediaid" id="mediaid">
    </div>

    <div class="btn-group">
    	<a href="javascript:;" class="btn btn1" id="btn2"></a>
    	<a href="order1-show.html" class="btn btn2"></a>
    </div>
    <!--<a class="btn btn2" id="oauth">用户授权测试</a>-->
    </div>
<div id="myModal" class="reveal-modal">
	<textarea name="myinfo2" id="myinfo2" rows="4"></textarea>
    <a class=" close-reveal-modal btn-submit" id="btn1" href="javascript:;">完成</a>
    
</div>	
</div>
    </form>
<style type="text/css">
	.reveal-modal .close-reveal-modal {
font-size: inherit;
line-height: normal;
position: absolute;
top: auto;
right: 9%;
color: #fff;
text-shadow: 0 -1px 1px rbga(0,0,0,.6);
font-weight: 200;
cursor: pointer;
}
input{ color:#fff}
</style>
<iframe name="doiframe" frameborder="0" style="display:none"></iframe>

<img id="img" style="display:none"/>

<script src="js/jquery.min.js"></script>
<script src="js/jquery.reveal.js"></script>
<script src="js/jquery.cookie.js"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
$(window).load(function(){
	$('body').css('display','block');
});

$("#oauth").click(function(){
	var rurl=encodeURI('xxx/reg/try/oauthdeal.php');
	oauthUrl='https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxx&redirect_uri='+rurl+'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
//	alert(oauthUrl)
	window.location.href=oauthUrl;
//	console.log(oauthUrl)
});	

wx.config({
    debug: false,
    appId: '<?php echo $signPackage["appId"];?>',
    timestamp: <?php echo $signPackage["timestamp"];?>,
    nonceStr: '<?php echo $signPackage["nonceStr"];?>',
    signature: '<?php echo $signPackage["signature"];?>',
    jsApiList: [
      // 所有要调用的 API 都要加到这个列表中
      'onMenuShareTimeline',
      'chooseImage',
      'uploadImage',
      'downloadImage'
    ]
  });
  wx.ready(function () {
    // 在这里调用 API
    wx.checkJsApi({
      jsApiList: [
        'getNetworkType',
        'chooseImage',
        'uploadImage'
      ],
      success: function (res) {
        console.log(JSON.stringify(res));
      }
    });
});
		
var images = {
    localId: [],
    serverId: []
};

if($.cookie('imgsrc')){
	$("#chooseImage").html('<img width="100%" height="100%" src="'+$.cookie('imgsrc')+'" id="expImg">')
}
				
$("#chooseImage").click(function(){
    wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
        success: function (res) {
            images.localId = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
            if (images.localId.length == 0) {
                alert('请先使用 chooseImage 接口选择图片');
                return false;
            }
            if(images.localId.length > 1) {
                alert('目前仅支持单张图片上传,请重新上传');
                images.localId = [];
                return false;
            }

            var i = 0, length = images.localId.length;
//					    images.serverId = [];

			$imgsrc=images.localId[0];
			$.cookie('imgsrc', images.localId[0]);
			$("#chooseImage").html('<img width="100%" height="100%" src="'+$imgsrc+'" id="expImg">')

            function upload() {
                wx.uploadImage({
                    localId: images.localId[i],
                    isShowProgressTips: 1, // 默认为1,显示进度提示
                    success: function (res) {
                        i++;
                        //						          that.siblings('img.preview').attr('src',images.localId[0]);
                        //				          alert('已上传:' + i + '/' + length);
                        images.serverId.push(res.serverId);
                        //		                  that.siblings('input[type=hidden]').val(images.serverId[0]);
                        $("#mediaid").val(images.serverId[0]);
//                                    alert(images.serverId[0])
                        if (i < length) {
                            upload();
                        }
                    },
                    fail: function (res) {
                        alert(JSON.stringify(res));
                    }
                });
            }
            upload();
        }
    });
});

$(function(){
     
	$("#btn1").click(function(){
		$("#myinfo").val($("#myinfo2").val());
	})
	
	$("#btn2").click(function(){
	
		if($("#tname").val()==''){
			alert('请输入姓名!');
			$("#tname").focus();
			return false;
		}
		var mobile=$("#mobile").val()
		var rp = /^1[3|5|8|7|9][0-9]\d{8,8}|147[0-9]\d{7,7}|170[0-9]\d{7,7}$/;
	 	 if (!rp.test(mobile) || mobile.length != 11) {
			alert("请输入格式正确的手机号码");
			$("#mobile").val("");
			$("#mobile").focus();
			return false;
		}
		if($("#myinfo").val()==''){
			alert('请输入自我介绍!');
			return false;
		}		
		if($("#mediaid").val()==''){
			alert('请输入上传个人照片!');
			return false;
		}		


         //创建FormData对象
         var datas = new FormData();
         //为FormData对象添加数据

         datas.append('action', 'add');
         datas.append('tname', $("#tname").val());
         datas.append('mobile', $("#mobile").val());
         datas.append('myinfo', $("#myinfo").val());
         datas.append('cartype', '1');
         datas.append('mediaid', $("#mediaid").val());
         
         $.ajax({
	        type: 'post',
	        async: false,
	        url: 'deal.php',
			contentType: false,    //不可缺
			processData: false,    //不可缺	        
			data: datas,
//	        dataType: "html",
	        success: function (data, status) {
				alert(data);
				window.location.reload();
	        },
	        error: function (data, status, e) {
	            console.log("系统异常" + data + e);
	        }
	    });
	})
});
	
    </script>
</body>
</html>


include('siteinit.php');

//表名
$tb='try';

$action=$_REQUEST['action'];
$sql="";

if($action=='add'){
	$tname=$_REQUEST['tname'];	
	$mobile=$_REQUEST['mobile'];	
	$myinfo=$_REQUEST['myinfo'];
	$cartype=$_REQUEST['cartype'];

        $MEDIA_ID = $_POST['mediaid'];
        $return = array();
        $path = './upload';//定义保存路径
        $dir = realpath($path);//为方便管理图片 保存图片时 已时间作一层目录作区分
        $tardir=$dir.'/'.date('Y_m_d');
        if(!file_exists($tardir)){
            mkdir($dir.'/'.date('Y_m_d'));
        }
        $ACCESS_TOKEN=$jssdk->getAccessToken();
        $url="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=$ACCESS_TOKEN&media_id=$MEDIA_ID";
//        var_dump($url);exit;
        $ch = curl_init($url);
		$ranfilename=time().rand().".jpg";
		$filename=$path.'/'.date('Y_m_d').'/'.$ranfilename;
		$tarfilename=$tardir."/".$ranfilename;
        $fp = fopen($tarfilename, "w");
		
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_HEADER, 0);

        curl_exec($ch);
        curl_close($ch);
        fclose($fp);
		
	$sql="insert into $tb(tname,mobile,myinfo,photo,cartype,addtime) values('$tname', '$mobile', '$myinfo', '$filename', '$cartype', UNIX_TIMESTAMP())";
//	exit($sql);
	$dbo=new Dbo();
	$result=$dbo->runSql($sql);
	if(!$result){
		exit('添加错误,请联系管理员!');
	}else{
		exit('提交完成');
	}
	
}

siteinit.php

include('../include/init.php');
$appid="xxx";
$appsecret="xxx";

require_once "jssdk.php";
$jssdk = new JSSDK($appid, $appsecret);
$signPackage = $jssdk->getSignPackage();
cjfmaster.com 2016-09-21
  • 打赏
  • 举报
回复
引用 1 楼 fictioner 的回复:

$MEDIA_ID = $_POST['mediaid'];
$return = array();
$path = './upload';//定义保存路径
$dir = realpath($path);//为方便管理图片 保存图片时 已时间作一层目录作区分
$tardir=$dir.'/'.date('Y_m_d');
if(!file_exists($tardir)){
mkdir($dir.'/'.date('Y_m_d'));
}
$ACCESS_TOKEN=$jssdk->getAccessToken();
$url="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=$ACCESS_TOKEN&media_id=$MEDIA_ID";
// var_dump($url);exit;
$ch = curl_init($url);
$ranfilename=time().rand().".jpg";
$filename=$path.'/'.date('Y_m_d').'/'.$ranfilename;
$tarfilename=$tardir."/".$ranfilename;
$fp = fopen($tarfilename, "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);


这段代码要封装在函数里在前端通过点击触发调用嘛?附上官方demo文件结构小白请大侠指教
fictioner 2016-09-20
  • 打赏
  • 举报
回复

        $MEDIA_ID = $_POST['mediaid'];
        $return = array();
        $path = './upload';//定义保存路径
        $dir = realpath($path);//为方便管理图片 保存图片时 已时间作一层目录作区分
        $tardir=$dir.'/'.date('Y_m_d');
        if(!file_exists($tardir)){
            mkdir($dir.'/'.date('Y_m_d'));
        }
        $ACCESS_TOKEN=$jssdk->getAccessToken();
        $url="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=$ACCESS_TOKEN&media_id=$MEDIA_ID";
//        var_dump($url);exit;
        $ch = curl_init($url);
		$ranfilename=time().rand().".jpg";
		$filename=$path.'/'.date('Y_m_d').'/'.$ranfilename;
		$tarfilename=$tardir."/".$ranfilename;
        $fp = fopen($tarfilename, "w");
		
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_HEADER, 0);

        curl_exec($ch);
        curl_close($ch);
        fclose($fp);

20,398

社区成员

发帖
与我相关
我的任务
社区描述
“超文本预处理器”,是在服务器端执行的脚本语言,尤其适用于Web开发并可嵌入HTML中。PHP语法利用了C、Java和Perl,该语言的主要目标是允许web开发人员快速编写动态网页。
phpphpstorm 技术论坛(原bbs)
社区管理员
  • 开源资源社区
  • phpstory
  • xuzuning
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧