微信小程序图片上传功能(PHP后端)
微信小程序图片上传功能(PHP后端)
文章目录
- 效果图
- 前端效果图
- 后端
- 代码
- wxml
- js
- php
效果图
前端效果图
后端
功能比较简单,解释都在注释里,这里就不进行讲解了
代码
wxml
<view class="main">
<image src='{{source}}'/>
<button bindtap="uploadimg">拍照或上传图片</button>
</view>
js
Page({data:{source:"",},// 上传图片uploadimg:function(){var that = this;// 从本地相册选择图片或者使用相机拍照wx.chooseImage({count: 1,sizeType:['original', 'compressed'] ,sourceType:['album', 'camera'],success:function(res){console.log("选择图片相应"+res);that.setData({source:res.tempFilePaths,});// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片 var tempFilePaths = res.tempFilePaths; wx.uploadFile({ url: 'https://www.yyl.plus/PestIdentify/api/', filePath: tempFilePaths[0], name: 'file', success:function(res){ //打印console.log("响应数据:");console.log(res.data);},})}})}
})
php
<?php
// 上传图片
function uploadimg() { $file = $_FILES['file'];// $file = request()->file('file');if ($file) { //var_dump($file);// 获取文件后缀名$ext = pathinfo($file['name'], PATHINFO_EXTENSION);$target = '../public/upload/weixin/' . uniqid() . '.' . $ext;// 转移图片地址if (!move_uploaded_file($file['tmp_name'], $target)) {$GLOBALS['error_message'] = '上传图片失败';echo error_message;}$res = ['errCode'=>0,'error_message'=>'图片上传成功','file'=>$target];$data = json_encode($res);var_dump($data); }
}uploadimg();