解决服务器中图片冗余的方法很多,本篇介绍利用七牛云自带的api解决图片冗余问题
问题:
在前端编辑富文本上传图片时,一般有两种方式,一种是将图片在本地预览,文件则在本地缓存,一种是直接上传服务器,然后将返回的图片地址展示。第一种明显消耗资源大且不稳定,易造成浏览器卡顿;而第二种是目前主流方式。对于第二种方式,在上传图片后,并不保存或者直接关闭浏览器,导致上传的图片一直滞留在服务器中,对服务器资源造成浪费。
解决:
通过七牛云api,在上传时将上传的文件改为临时存储,设为一天后自动删除
当用户保存富文本时,再将图片改为永久存储;在用户保存时,再将图片转为永久存储
核心代码:
设为临时存储或者永久存储
<?php
//封装的方法
require ('../../methods/public_methods.php');
require('../../methods/qiniu_sdk/autoload.php');
use Qiniu\Auth;
//获取参数
$img_arr=var_is_null2('post','img_arr');//获取参数
$day=var_is_null2('post','day');
if($day==1000){
$day=0;
}
// 用于签名的公钥和私钥
$accessKey = '';
$secretKey = '';
$bucket='';
$auth = new Auth($accessKey, $secretKey);
$config = new \Qiniu\Config();
$bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
//每次最多不能超过1000个
$img_arr = explode(",", $img_arr);
$keys = $img_arr;
$keyDayPairs = array();
//day=0表示永久存储
foreach ($keys as $key) {
$keyDayPairs[$key] = $day;
}
$ops = $bucketManager->buildBatchDeleteAfterDays($bucket, $keyDayPairs);
list($ret, $err) = $bucketManager->batch($ops);
if ($err) {
echo $err;
} else {
echo $ret;
}
删除文件
<?php
//封装的方法
require ('../../methods/public_methods.php');
require('../../methods/qiniu_sdk/autoload.php');
use Qiniu\Auth;
//获取参数
$img_arr=var_is_null2('post','del_img_arr');//获取参数
// 用于签名的公钥和私钥
$accessKey = '';
$secretKey = '';
$bucket='';
$auth = new Auth($accessKey, $secretKey);
$config = new \Qiniu\Config();
$bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
//每次最多不能超过1000个
$img_arr = explode(",", $img_arr);
$keys = $img_arr;
$ops = $bucketManager->buildBatchDelete($bucket, $keys);
list($ret, $err) = $bucketManager->batch($ops);
if ($err) {
echo $err;
} else {
echo $ret;
}
js:从富文本中获取key值
// 获取富文本图片地址
getImgSrc (cont) {
let richtext= cont.replace(/"/g, "'")
let imgList = []
richtext.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
imgList.push(this.$m.queStr(capture, 'https://cdn.weblf.cn/', true))
})
return imgList
},