一、php后端
修改php项目config文件夹中app.php
Image的Controller层中的uploadMore方法
// 上传多图
public function uploadMore()
{
$list = (new ImageModel())->uploadMore();
return self::showResCode('上传成功', ['list' => $list]);
}
Image的Model层中uploadMore与upload方法:
// 自动写入时间
protected $autoWriteTimestamp = true;
// 上传多图
public function uploadMore()
{
$image = $this->upload(request()->userId, 'imglist');
for ($i = 0; $i < count($image); $i++) {
$image[$i]['url'] = getFileUrl($image[$i]['url']);
}
return $image;
}
// 上传图片
public function upload($userid = '', $field = '')
{
// 获取图片
$files = request()->file($field);
if (is_array($files)) {
// 多图上传
$arr = [];
foreach ($files as $file) {
$res = \app\common\controller\FileController::UploadEvent($file);
if ($res['status']) {
$arr[] = [
'url' => $res['data'],
'user_id' => $userid
];
}
}
return $this->saveAll($arr);
}
// 单图上传
if (!$files)
TApiException('请选择要上传的图片', 10000, 200);
// 单文件上传
$file = \app\common\controller\FileController::UploadEvent($files);
// 上传失败
if (!$file['status'])
TApiException($file['data'], 10000, 200);
// 上传成功,写入数据库
return self::create([
'url' => $file['data'],
'user_id' => $userid
]);
}
// 图片是否存在
public function isImageExist($id, $userid)
{
return $this->where('user_id', $userid)->field('id')->find($id);
}
TApiException方法在common.php中
// 异常类输出函数
function TApiException($msg = '异常', $errorCode = 999, $code = 400)
{
throw new \app\lib\exception\BaseException(['code' => $code, 'msg' => $msg, 'errorCode' => $errorCode]);
}
二、uniapp前端
import下方内容,定义变量sourceType与sizeType
var sourceType = [
['camera'],
['album'],
['camera', 'album']
]
var sizeType = [
['compressed'],
['original'],
['compressed', 'original']
]
data数据定义:
imageList: [],
sourceTypeIndex: 2,
sizeTypeIndex: 2,
countIndex: 8,
count: [1, 2, 3, 4, 5, 6, 7, 8, 9]
方法:
chooseImage: async function() {
// #ifdef APP-PLUS
// TODO 选择相机或相册时 需要弹出actionsheet,目前无法获得是相机还是相册,在失败回调中处理
if (this.sourceTypeIndex !== 2) {
let status = await this.checkPermission();
if (status !== 1) {
return;
}
}
// #endif
if (this.imageList.length === 9) {
let isContinue = await this.isFullImg();
console.log("是否继续?", isContinue);
if (!isContinue) {
return;
}
}
uni.chooseImage({
sourceType: sourceType[this.sourceTypeIndex],
sizeType: sizeType[this.sizeTypeIndex],
count: this.imageList.length + this.count[this.countIndex] > 9 ? 9 - this.imageList.length : this.count[this.countIndex],
success: (res) => {
// 上传图片
// console.log(res);
res.tempFilePaths.forEach(item=>{
this.$H.upload('/image/uploadmore',{
filePath: item,
name: 'imglist[]',
token: true
}).then(result=>{
console.log(result);
})
})
// this.imageList = this.imageList.concat();
// this.$emit('change',this.imageList);
},
fail: (err) => {
console.log("err: ",err);
// #ifdef APP-PLUS
if (err['code'] && err.code !== 0 && this.sourceTypeIndex === 2) {
this.checkPermission(err.code);
}
// #endif
// #ifdef MP
if(err.errMsg.indexOf('cancel') !== '-1'){
return;
}
uni.getSetting({
success: (res) => {
let authStatus = false;
switch (this.sourceTypeIndex) {
case 0:
authStatus = res.authSetting['scope.camera'];
break;
case 1:
authStatus = res.authSetting['scope.album'];
break;
case 2:
authStatus = res.authSetting['scope.album'] && res.authSetting['scope.camera'];
break;
default:
break;
}
if (!authStatus) {
uni.showModal({
title: '授权失败',
content: 'Hello uni-app需要从您的相机或相册获取图片,请在设置界面打开相关权限',
success: (res) => {
if (res.confirm) {
uni.openSetting()
}
}
})
}
}
})
// #endif
}
})
},
isFullImg: function() {
return new Promise((res) => {
uni.showModal({
content: "已经有9张图片了,是否清空现有图片?",
success: (e) => {
if (e.confirm) {
this.imageList = [];
res(true);
} else {
res(false)
}
},
fail: () => {
res(false)
}
})
})
},
async checkPermission(code) {
let type = code ? code - 1 : this.sourceTypeIndex;
let status = permision.isIOS ? await permision.requestIOS(sourceType[type][0]) :
await permision.requestAndroid(type === 0 ? 'android.permission.CAMERA' :
'android.permission.READ_EXTERNAL_STORAGE');
if (status === null || status === 1) {
status = 1;
} else {
uni.showModal({
content: "没有开启权限",
confirmText: "设置",
success: function(res) {
if (res.confirm) {
permision.gotoAppSetting();
}
}
})
}
return status;
}