微信小程序上传图片到php服务器的方法

submitPhoto(){ var that = this; wx.uploadFile({ url: 'http://xxx.cn/upload.php', //仅为示例,非真实的接口地址 filePath: imagePath, name: 'imgfile', success: function (res) { var data = JSON.parse(res.data);; console.log(data); //do something if(data.code==1){ wx.showToast({ title: '成功', icon: 'success', duration: 1000 }) } } }) },

PHP代码如下upload.php

<?php /** * 上传图片 * 图像识别 * https://cloud.tencent.com/document/product/641/12438 * * Created by PhpStorm. * User: caydencui * Date: 2018/1/26 * Time: 9:52 */ header('Content-Type:text/html;charset=utf-8'); class Response{ public static function json($code,$message="",$data=array()){ $result=array( 'code'=>$code, 'message'=>$message, 'data'=>$data ); //输出json echo json_encode($result); exit; } } $uplad_tmp_name=$_FILES['imgfile']['tmp_name']; $uplad_name =$_FILES['imgfile']['name']; $image_url=""; //上传文件类型列表 $uptypes=array( 'image/jpg', 'image/jpeg', 'image/png', 'image/pjpeg', 'image/gif', 'image/bmp', 'image/x-png' ); //图片目录 $img_dir="upload/"; //……html显示上传界面 /*图片上传处理*/ //把图片传到服务器 //初始化变量 $date = date(ymdhis); $uploaded=0; $unuploaded=0; //上传文件路径 $img_url="http://test.cayden.cn/upload/"; //如果当前图片不为空 if(!empty($uplad_name)) { //判断上传的图片的类型是不是jpg,gif,png,bmp中的一种,同时判断是否上传成功 // if(in_array($_FILES['imgfile']["type"][$i], $uptypes)) // { $uptype = explode(".",$uplad_name); $newname = $date."-0".".".$uptype[1]; //echo($newname); $uplad_name= $newname; //如果上传的文件没有在服务器上存在 if(!file_exists($img_dir.$uplad_name)) { //把图片文件从临时文件夹中转移到我们指定上传的目录中 $file=$img_dir.$uplad_name; move_uploaded_file($uplad_tmp_name,$file); chmod($file,0644); $img_url1=$img_url.$newname; $uploaded++; Response::json(1,'success',$img_url1); } // } // else // { // Response::json(1,'type error',$img_url1); // $unuploaded++; // } }//endif Response::json(0,'error',$img_url1); ?>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/1665b91ed654840df7be1ce17bd5b95e.html