TP5.1 腾讯云 数据定时删除
文件 = 图片/视频
定时删除思路:
1 . 获取腾讯云里所有的文件
2 . 查询数据库里面有的文件
3 . 求差集,然后每日删除
先封装一个 腾讯云Cos

class CosUpload extends Controller
{
private $secretId = "API 密钥 SecretId";
private $secretKey = "API 密钥 SecretKey";
private $region = "地域"; // 地区 ap-guangzhou
private $bucket = "存储桶名称"; //存储桶名称 格式:BucketName-APPID
public function init()
{
// 配置参数
$this->secretId = config('QCLOUD_COS.secretId');
$this->secretKey = config('QCLOUD_COS.secretKey');
$this->region = config('QCLOUD_COS.region');
$this->bucket = config('QCLOUD_COS.bucket');
return $cosClient = new Client([
'schema' => 'http', //协议头部,默认为http
'region' => $this->region,
'credentials' => array(
'secretId' => $this->secretId,
'secretKey' => $this->secretKey
)
]);
}
/**
* 查看当前目录下的所有文件
*
* @param $catalog // 目录 /Admin
*/
public function list($catalog = '')
{
$cos = $this->init();
$result = $cos->listObjects(array(
'Bucket' => $this->bucket, //格式:BucketName-APPID
'Delimiter' => '',
'EncodingType' => 'url',
'Marker' => '',
'Prefix' => $catalog,
'MaxKeys' => 1000,
));
$all = [];
foreach ($result['Contents'] as $k => $v) {
$all[] = ($v['Key']);
}
return $all;
}
/**
* 单文件上传,返回文件路径
*
* @param $request
* @param $param //请求参数名 photo
* @param $catalog //数据表目录名 diary等
*/
public function upload($request, $param, $catalog,$complete = null)
{
$file = $request->file($param); //前端参数名name = $param
$this->fileValidate($file); //验证文件
try {
$cosClient = $this->init();
// 桶名
// 唯一key 比如目录: EmpMidImg/48f5ff932b3dba19a6345055af2fd6de.jpg
// body //文件数据
$result = $cosClient->Upload(
$bucket = $this->bucket,
$key = $catalog .'/'.date("Ymd").'/'. md5(uniqid()) . '.' . pathinfo($file->getInfo()['name'], PATHINFO_EXTENSION),
$body = fopen($file->getFileInfo(), "rb")
);
if($complete)
return 'https://'.$result['Location'];
else
return $result['Key'];
} catch (\Exception $e) {
return failApi($e->getMessage());
}
}
public function delete($url){ //获取删除图的key
$key = $url; // 域名后的目录 EmpMidImg/48f5ff932b3dba19a6345055af2fd6de.jpg
//获取储存桶对象
$cosClient = $this->init();
try {
$cosClient->deleteObject(array(
'Bucket' => $this->bucket,//存储桶名称
'Key' => $key,
));
// 请求成功
return sucApi('删除成功');
} catch (\Exception $e) {
return failApi($e->getMessage());
}
}
public function fileValidate($file) //自定义文件验证类
{
if (!$file || !($file->getInfo())) //不为空且为文件类型
failApi('上传错误!')->send();
$rule = ['BMP', 'JPG', 'JPEG', 'PNG', 'GIF','AVI','MOV','RMVB','RM','FLV','MP4','3GP']; //规定格式
$ext = strstr(strrev($file->getInfo()['name']), '.', true); //倒序截取,获取后缀
$ext = strrev(strtoupper($ext)); //再倒序和变成大写后缀
if ($file->getInfo()['size'] > 1073741824) //文件小于10m
{
failApi('文件不能超过10m!')->send();
die;
}
if (!in_array($ext, $rule)) //是否为这些文件类型
{
failApi('文件类型错误!')->send();
die;
}
}
}
使用:
class ClearCosFile extends Command
{
protected function configure()
{
// 指令配置
$this->setName('ClearCosFile');
}
protected function execute(Input $input, Output $output)
{
$start = microtime(true); //计时间
$this->clearExtraImg(new Admin, 'Admin');
$this->clearExtraImg(new ErGrants, 'ErGrants');
$this->clearExtraImg(new ErPolicy, 'ErPolicy');
$end = microtime(true);
$usedTime = bcsub($end, $start, 4); //计时间
$this->logs('执行总时间为:'.$usedTime);
}
/**
* 清除云上 数据库不使用的图片
* @param $obj // 表对象
* @param $catalog // 目录
*/
public function clearExtraImg($obj, $catalog)
{
$cosObj = new CosUpload();
try {
//https://桶名.cos.ap-guangzhou.myqcloud.com/ErDetailImg/20210807/785cb63349b8dc6e609708bc5d6d92f7.jpg
// 1.获得已使用
$arr = $obj->field('head_img as url')->select()->toArray();
array_walk($arr, function ($v, $k) use (&$used) {
$used[] = $v['url'];
});
// 2.获得所有
$all = $cosObj->list($catalog);
// 3.求差集然后删除
$remain = array_diff($all, $used);
if (count($remain)) {
foreach ($remain as $k => $v) {
$cosObj->delete($v);
}
}
unset($cos);
} catch (\Exception $e) {
// 请求失败
$this->logs('报错信息是:' . $e->getMessage() . ',终止运行'.$catalog, 'error');
return failApi($e->getMessage());
}
}
//写日志
public function logs($msg, $type = 'info')
{
Log::init([
'type' => 'File',
'path' => Env::get('root_path') . 'CosClearLogs',
'max_files' => 20,
]);
Log::write($msg, $type);
Log::close();
}
}
上传
public function upload()
{
$url = (new CosUpload)->upload($this->request, 'img', '/Admin/'); //获得新封面
return sucApi($url);
}
(定时任务教学在我的随笔里)


浙公网安备 33010602011771号