引言:在微信小程序中選擇手機圖片并上傳到后臺
主要步驟:
- 使用wx.chooseImage來選擇圖片
- 使用wx.uploadFile來上傳圖片
選擇圖片
<button bindtap='handleChooseAlbum' size="mini" >選擇圖片</button>
handleChooseAlbum(){
//系統(tǒng)API,讓用戶在相冊中選擇圖片(或者拍照)
wx.chooseImage({
success : (res) => {
//1、取出路徑
const path = res.tempFilePaths
console.log(res)
//2、設(shè)置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 服務(wù)器地址
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';
//創(chuàng)建文件夾(按年月)
$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));
//存儲到數(shù)據(jù)庫
$img_url = '/upload/images'.$name.$filename;
$insert = [
'filename' => $img_url,
'shoper_id' => $shoper_id,
'add_time' => time()
];
Db::name('shoper_images')->insert($insert);
}
}