小程序以其轻量快捷的优点成为热门开发向,但以其特有的封装,让很多新手比较迷茫。本文以php后端来实现一个简单的小程序图片上传,让大家更为清楚地了解小程序开发。
一、wxml文件
<text>上传图片</text>
<view>
<button bindtap="uploadimg">点击选择上传图</button>
</view>
<image src='{{source}}' style='width:600rpx; height:600rpx' />二、js文件
Page({
/**
* 页面的初始数据
*/
data: {
//初始化为空
source:''
},
/**
* 上传图片
*/
uploadimg:function(){
var that = this;
wx.chooseImage({ //从本地相册选择图片或使用相机拍照
count: 1, // 默认9
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: 'http://www.website.com/home/api/uploadimg',
filePath: tempFilePaths[0],
name: 'file',
success:function(res){
//打印
console.log(res.data)
}
})
}
})
},
)}三、PHP后端代码
// 上传图片
public function uploadimg()
{
$file = request()->file('file');
if ($file) {
$info = $file->move('public/upload/weixin/');
if ($info) {
$file = $info->getSaveName();
$res = ['errCode'=>0,'errMsg'=>'图片上传成功','file'=>$file];
return json($res);
}
}
}
立即学习“PHP免费学习笔记(深入)”;
相关阅读:
微信是一款手机通信软件,支持通过手机网络发送语音短信、视频、图片和文字。微信可以单聊及群聊,还能根据地理位置找到附近的人,带给大家全新的移动沟通体验,有需要的小伙伴快来保存下载体验吧!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号