原地址:https://help.aliyun.com/document_detail/88473.html?spm=a2c4g.11186623.6.1090.316c145eysHW9d
方法封装:
public function uploads(Request $request) { $pictrue = ''; // 获取图片转base64的字符串 $result = []; // 转化base64编码图片 jpeg、jpg、png、bmp、gif if(preg_match('/^(data:s*image/(w+);base64,)/', $pictrue, $result)) { $type = $result[2]; // 获取图片类型 if(in_array($type, array('pjpeg','jpeg','jpg','bmp','png'))) { // 图片名字 $fileName = time().rand(1,1000).'.'.$type; // 图片名称 // 临时文件 $tmpfname = tempname("./image/", "FOO"); // windows $tmpfname = ('/tmp/', 'FOO'); // linux // 保存图片 $handle = fopen($tmpfname, "w"); // return [$pic, $result]; $object = 'school/avatar/'.date('Y/m/d').'/'.$fileName; // 阿里云上传地址 if (fwrite($handle, base64_decode(str_replace($result[1], '', $pic)))) { // 上传图片至阿里云OSS $ossClient = new Aliyunoss(); $data = $ossClient->uploads($object, $tmpfname); // return [$pic, $result, $data]; // 关闭缓存 fclose($handle); // 删除本地该图片 unlink($tmpfname); // 返回图片链接 return StatusCode::getCode(0, ['data' => $data]); }else { return response(['message'=>'图片上传失败'], 200); } }else { return response(['message'=>'图片类型错误'], 200); } } else { return response(['message'=>'图片编码错误'], 200); } }
阿里云OSS
public function uploads($object, $content) { $ossClient = self::getOssClient(); if (is_null($ossClient)) exit(1); $bucket = self::getBucketName(); try{ $ossClient->uploadFile($bucket, $object, $content); } catch(OssException $e) { self::println(__FUNCTION__ . ": FAILED "); self::println($e->getMessage() . " "); $object = 'error'; } return $object; }