官网文档
https://developers.weixin.qq....
index.wxml
<view class="container"> <button bindtap="imgupload">上传图片</button></view>
index.js
const app = getApp()Page({ data: { }, imgupload(){ wx.chooseImage({ success (res) { // 获取选取的图片 const tempFilePaths = res.tempFilePaths // 循环上传每一张选取的图片 for (var i = 0; i < tempFilePaths.length; i++) { wx.uploadFile({ url: '你的上传服务端https接口', filePath: tempFilePaths[i], name: 'file', success (res){ const msg = JSON.parse(res.data).msg; const url = JSON.parse(res.data).url; const code = JSON.parse(res.data).code; if(JSON.parse(res.data).code == 200){ wx.showToast({ title: '胜利', icon: 'success', duration: 1000 }) console.log(url) }else{ wx.showToast({ title: '上传失败', icon: 'error', duration: 1000 }) } console.log(msg) } }) } } }) }})
index.php
<?phpheader("Content-Type:application/json");// 容许上传的图片后缀$allowedExts = array("jpeg", "jpg", "png");// 后缀名if ($allowedExts[0] == 'jpeg') { $hzm = 'jpg';}else{ $hzm = $allowedExts[0];}// 获取抉择的文件$temp = explode(".", $_FILES["file"]["name"]);// 获取文件后缀名$extension = end($temp);if ((($_FILES["file"]["type"] == "image/gif")|| ($_FILES["file"]["type"] == "image/jpeg")|| ($_FILES["file"]["type"] == "image/jpg")|| ($_FILES["file"]["type"] == "image/pjpeg")|| ($_FILES["file"]["type"] == "image/x-png")|| ($_FILES["file"]["type"] == "image/png"))&& ($_FILES["file"]["size"] < 10485760) // 最大能够上传10MB&& in_array($extension, $allowedExts)){ if ($_FILES["file"]["error"] > 0) { $result = array( 'code' => 201, 'msg' => '上传失败'.$_FILES["file"]["error"] ); } else { // 判断当前目录下的 upload 目录是否存在该文件 // 如果没有 upload 目录,你须要创立它,upload 目录权限为 777 if (file_exists("upload/" . $_FILES["file"]["name"])) { $result = array( 'code' => 202, 'msg' => '文件已存在' ); } else { // 如果 upload 目录不存在该文件则将文件上传到 upload 目录下 $new_file = date("Y-m-d")."-".rand(10000,99999).".".$hzm; move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$new_file); $result = array( 'code' => 200, 'msg' => '上传胜利', 'url' => '这里是图片门路,本人批改你的后端代码门路'.$new_file ); } }}else{ $result = array( 'code' => 203, 'msg' => '不反对的文件格式' );}echo json_encode($result,JSON_UNESCAPED_UNICODE);?>
应用阐明
(1)后端代码须要在外面批改你的代码上传到服务器所在的门路,能力失常显示上传胜利的图片地址,例如你的代码上传到服务器根目录下img目录,那么你须要将门路批改为http://域名/img/upload
(2)还须要在index.php的同一目录下新建一个名为upload文件夹,这个是用来寄存上传后的图片文件的。
Author:TANKING
Date:2021-04-14
WeChat:sansure2016
Web:http://www.likeyun.cn/