补单系统涉及到的图片非常多,把图片上传到七牛云可以大大节省服务器空间!
public function submitImg()
{
$type = input('type', 0);
if ($type <= 0) {
return json(['status' => -1, 'msg' => '无效参数']);
} else {
$file = request()->file('file');
//验证文件格式
$result = $this->validate(['file' => $file], ['file'=>'require|image'],['file.require' => '请选择上传文件', 'file.image' => '非法图像文件']);
if(true !== $result){
$this->error($result);
}
if ($file) {
switch ($type) {
case 1:
// 商家意见
$folderName = 'suggestion';
break;
case 2:
// 商家充值
$folderName = 'business_recharge';
break;
default:
$folderName = '';
break;
}
// 要上传图片的本地路径
$filePath = $file->getRealPath();
$ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION); //后缀
// 上传到七牛后保存的文件名
$key = $folderName. '/' . substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
// 需要填写你的 Access Key 和 Secret Key
$accessKey = config('ACCESSKEY');
$secretKey = config('SECRETKEY');
// 构建鉴权对象
$auth = new Auth($accessKey, $secretKey);
// 要上传的空间
$bucket = config('BUCKET');
$domain = config('DOMAIN');
$token = $auth->uploadToken($bucket);
// 初始化 UploadManager 对象并进行文件的上传
$uploadMgr = new UploadManager();
// 调用 UploadManager 的 putFile 方法进行文件的上传
list($imgUrl, $err) = $uploadMgr->putFile($token, $key, $filePath);
// dump($err);
if ($err !== null) {
return json(['status' => 0, 'msg' => '上传失败,请重新上传']);
} else {
//返回图片的完整URL
return json(['status' => 1, 'msg' => '上传成功', 'imgUrl' => $domain . '/' . $imgUrl['key']]);
}
} else {
return json(['status' => 0, 'msg' => '上传失败,请重新上传,只能上传jpg,png,gif格式']);
}
}
}