1、下载OSS文件放在网站根目录下(OSS文件下载地址:https://gitee.com/jth1234/oss_files.git)
2、在入口文件中加载OSS
3、config文件配置oss信息(ossKeyId、ossKeySecret、endpoint以上信息开通阿里云oss服务后可获得;bucket是创建的存储目录名)
4、上传base64图片(UploadController.php)
<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
use OSS\OssClient;
use OSS\Core\OssException;
class UploadController extends Controller {
/**
* 上传图片到oss
* @param string $info base64图片
*
*/
public function upload_pic(){
$imgData = input('info','');
if($imgData){
$img_len = strlen($imgData);
$imgData = str_replace('\n','',$imgData);
$imgData = str_replace('\r','',$imgData);
$imgData = str_replace('\t','',$imgData);
$imgData = str_replace(PHP_EOL,'',$imgData);
$imgData = str_replace('\\','',$imgData);
$imgData = str_replace(' ','+',$imgData); $host = config('public.host'); $date = date('Y-m-d');
$dir = "./public/user/$date";
if (!file_exists($dir)){
mkdir ($dir,0777,true);
}
$img = base64_decode($imgData);
$uniqid_name = md5(uniqid(rand()));
$tmpImg = './public/user/'.$date.'/user_'.$uniqid_name.'.jpg';
$tmpImg1 = '/public/user/'.$date.'/user_'.$uniqid_name.'.jpg';
$a = file_put_contents($tmpImg,$img);//保存图片,返回的是字节数
if($a){
$accessKeyId = config('oss.ossKeyId');
$accessKeySecret = config('oss.ossKeySecret');
// Endpoint以杭州为例,其它Region请按实际情况填写。
$endpoint = config('oss.endpoint');
// 存储空间名称
$bucket= config('oss.bucket');
// 文件名称
$object = 'user/'.$date.'/user_'.$uniqid_name.'.jpg';
// <yourLocalFile>由本地文件路径加文件名包括后缀组成,例如/users/local/myfile.txt
$filePath = './public/user/'.$date.'/user_'.$uniqid_name.'.jpg';
try{
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$ossClient->uploadFile($bucket, $object, $filePath);
unlink($filePath);
} catch(OssException $e) {
$data=array('code'=>config('code.error'),'msg'=>"上传失败");
return json($data);
}
$img_src = config('oss.host')."/".$object;
$data=array('code'=>config('code.success'),'msg'=>"上传成功",'data'=>$img_src);
return json($data);
}else{
$data=array('code'=>config('code.error'),'msg'=>"上传失败");
return json($data);
}
}else{
$data=array('code'=>config('code.error'),'msg'=>"上传图片不能为空");
return json($data);
}
}
/**
* 删除OSS上的图片
* @param string $info OSS上完整的图片地址
*
*/
public function pic_del(){
$info = input('pic_addr','');
if(!empty($info)){
$ex = config('oss.host').'/';
$arr = explode($ex,$info);
$accessKeyId = config('oss.ossKeyId');
$accessKeySecret = config('oss.ossKeySecret');
$endpoint = config('oss.endpoint');
$bucket= config('oss.bucket');
$object = $arr[1];
try{
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$ossClient->deleteObject($bucket, $object);
} catch(OssException $e) {
printf(__FUNCTION__ . ": initiateMultipartUpload, uploadPart - part#{$i} FAILED\n");
printf($e->getMessage() . "\n");
return;
}
}
$data=array('code'=>config('code.success'),'msg'=>"删除成功");
return json($data);
}
}