js代碼
bindViewTap: function () {
var that = this;
console.log(that.data.hits)
var hit = that.data.hits
hit = hit+1;
that.setData({
hits:hit
})
// 多張圖片
if (hit <= 3) {
wx.chooseImage({
count: 3,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success(res) {
// tempFilePath可以作爲img標籤的src屬性顯示圖片
const tempFilePaths = res.tempFilePaths;
that.data.imgsrc.push(tempFilePaths);
var list = [];
that.data.imgsrc.forEach(function (item, index) {
//這裏的item就是從數組裏拿出來的每一個數組
var obj = {
'filesrc': item[0],
}
list.push(obj);
that.setData({
family: list,
})
})
console.log(that.data.family);
// 成功之後上傳到服務器
wx.uploadFile({
url: app.globalData.requesturl,
filePath: tempFilePaths[0],
name: 'file',
formData: {
'method': 'addImg'
},
success: function (res) {
var data = JSON.parse(res.data);
console.log(data);
if(data.status == 3) {
that.data.iurl.push(data.url);
var itemp = '';
that.data.iurl.forEach(function (item2, index2) {
//這裏的item就是從數組裏拿出來的每一個數組
// console.log(item2);
var list2 = item2 + ',' + itemp;
itemp = list2;
});
that.setData({
iurlall: itemp,
});
console.log(that.data.iurlall);
}else if (data.statu == 2){
wx.showToast({
title: '上傳圖片不能大於1M!'
})
} else if (data.statu == 1) {
wx.showToast({
title: '格式錯誤',
})
} else if (data.statu == 4) {
wx.showToast({
title: '上傳失敗',
})
} else if (data.statu == 6) {
wx.showToast({
title: '上傳方式錯誤',
})
}
}
});
}
});
} else {
wx.showToast({
title: '最多可上傳3張圖片',
})
}
},
wxml代碼
<view bind:tap="bindViewTap" class='clear' style='width:100%;'>點我上傳</view>
php接口
function addImg() {
$code = $_FILES['file'];//獲取小程序傳來的文件
// return $_FILES['file']['type'];
// 判斷是否是post提交
if(is_uploaded_file($_FILES['file']['tmp_name'])) {
//臨時文件
$uploaded_file = $_FILES['file']['tmp_name'];
// return $uploaded_file;
// 允許的圖片類型
$judge_img = array("image/gif","image/pjpeg","image/jpeg","image/png","image/jpg");
// 允許的視頻類型
$judge_vid = array("video/mp4");
// 判斷是圖片還是視頻
if(in_array($_FILES['file']['type'],$judge_img)) {
// 換算字節 1M = 1024KB;1KB = 1000bt;
if($_FILES["file"]["size"] > 1024000) {
// 圖片過大
$arr = ['status' => 2];
return $arr;
}
// 圖片的路徑
$user_path = DT_ROOT."/include/jjapp/upload/img/";
}elseif(in_array($_FILES['file']['type'],$judge_vid)) {
if($_FILES["file"]["size"] > 2048*1000) {
// 視頻過大
$arr = ['status' => 2];
return $arr;
}
// 視頻的路徑
$user_path = DT_ROOT."/include/jjapp/upload/video/";
}else {
// 格式錯誤
$arr = ['status' => 1];
return $arr;
}
$file_true_name = $_FILES['file']['name'];
$move_to_file = $user_path.time()."-".date("Y-m-d").substr($file_true_name,strrpos($file_true_name,"."));
if(move_uploaded_file($uploaded_file,iconv("utf-8","gb2312",$move_to_file))) {
// 上傳成功
$arr = ['status' => 3, 'url' => $move_to_file];
return $arr;
} else {
// 上傳失敗網絡錯誤,請重新上傳
$arr = ['status' => 4];
return $arr;
}
} else {
// 上傳方式錯誤
$arr = ['status' => 6];
return $arr;
}
}