1、控制器 OssImageController.php(不必关注此层)
<?php
declare(strict_types = 1);
namespace app\controllers;
use app\services\OssImageService;
class OssImageController extends BaseController
{/*** oss 批量删除图片** @throws null*/public function actionDelImage(){$data = OssImageService::service()->batchDelImage($this->params);$this->response([], $data['status'], $data['msg']);}
}
2、service 层 OssImageService.php(业务实现层)
<?php
declare(strict_types = 1);
namespace app\services;
use app\extensions\AliOss;
use app\extensions\Helper;
class OssImageService extends BaseService
{/*** 批量删除oss图片** @param array $params* @return array* @throws null*/public function batchDelImage(array $params){/*$params['images'] = ['https://hk-server.oss-cn-hongkong.aliyuncs.com/blog/article-in/2018-08-23/010494376.jpg','https://hk-server.oss-cn-hongkong.aliyuncs.com/blog/article-in/2018-08-23/011832527.jpg'];*/if (!isset($params['images']) || empty($params['images'])) {return Helper::msg(0, '请选择需要删除的图片');}if (!is_array($params['images'])) {return Helper::msg(0, '删除图片格式错误,请传数组格式');}$ossHttpUrl = 'https://'.AliOss::bucket.'.'.AliOss::endpoint.'/';$ossHttpsUrl = 'http://'.AliOss::bucket.'.'.AliOss::endpoint.'/';$objectArray = $params['images'];// 将每一个链接的协议+bucketName+endpoint替换成'' (即去掉这部分string)foreach ($objectArray as &$v) {$v = str_replace($ossHttpUrl, '', $v);$v = str_replace($ossHttpsUrl, '', $v);}$ossClient = AliOss::getOssClient();$bucketName = AliOss::getBucketName();// 执行批量删除$ossClient->deleteObjects($bucketName, $objectArray);return Helper::msg(1, '删除素材图片成功');}
}
3、说明
虽然阿里云 oss 提供了批量删除文件的方法,但这里仍然不建议使用,因为存在着操作风险,建议删除文件的操作还是在控制台手动操作。
注:免费领取阿里云产品优惠券:https://www.haveyb.com/aliyun