引言:在微信小程序中选择手机图片并上传到后台
主要步骤:
- 使用wx.chooseImage来选择图片
- 使用wx.uploadFile来上传图片
选择图片
<button bindtap='handleChooseAlbum' size="mini" >选择图片</button>
handleChooseAlbum(){
//系统API,让用户在相册中选择图片(或者拍照)
wx.chooseImage({
success : (res) => {
//1、取出路径
const path = res.tempFilePaths
console.log(res)
//2、设置imagePath
this.setData({
imagePath : path
})
}
})
},
上传图片(多张)
uploadimg:function(shoper_id){
var that = this
for (var i = 0; i < that.data.imagePath.length; i++) {
var imgUrl = that.data.imagePath[i];
wx.uploadFile({
//php 服务器地址
url: config.url + 'shoper/saveimg',
filePath: imgUrl,
name: 'file',
formData: {
'shoper_id': shoper_id
},
success: function (res) {
console.log("success");
},
fail: function (res) {
console.log("error");
}
})
}
},
后台
//存储图片
public function saveimg()
{
//处理图片
$imgs = $_FILES['file'];
$shoper_id = $_REQUEST['shoper_id'];
if($imgs){
$destination = $_SERVER['DOCUMENT_ROOT'].'/static/upload/images';
//创建文件夹(按年月)
$name = "/shoper/".date("Ym")."/";
$ymname = $destination.$name;
if(!is_dir($ymname)){
mkdir($ymname,0777,true);
}
//文件名称
$filename = date("YmdHis",time()).'-'.substr(md5($imgs['name']),0,10).'.jpg';
//存储到文件夹,$imgs['tmp_name']是小程序端传来的图片临时路径
move_uploaded_file($imgs['tmp_name'], $ymname.'/' . iconv("UTF-8", "gb2312", $filename));
//存储到数据库
$img_url = '/upload/images'.$name.$filename;
$insert = [
'filename' => $img_url,
'shoper_id' => $shoper_id,
'add_time' => time()
];
Db::name('shoper_images')->insert($insert);
}
}