本文實例為大家分享了微信小程序上傳圖片到php服務器的具體代碼,供大家參考,具體內容如下
js代碼如下
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);?>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答