我使用ueditor作為富文本編輯器,配置已經好了,上傳功能也好了。
現在的問題是當使用ueditor上傳圖片的時候,選擇了圖片就立刻上傳到指定的文件夾里,而后續即使沒有保存該篇文章內容,即取消操作,圖片還是上傳了,就相當於上傳的圖片是無用的,沒有給任何文章或者用戶來使用,該如何刪除這些無用的圖片啊?限制圖片的自動上傳?
研究了半天,終於搞定了,主要思路是先把圖片存放到臨時文件夾ueditor_temp里,然后提交的時候通過正則表達式遍歷的方式匹配查找圖片,然后把圖片轉移到實際的文件夾中。
$content=$_POST['content']; if(!empty($content)) { //正則表達式匹配查找圖片路徑 $pattern='/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.jpeg|\.png]))[\'|\"].*?[\/]?>/i'; preg_match_all($pattern,$content,$res); $num=count($res[1]); for($i=0;$i<$num;$i++) { $ueditor_img=$res[1][$i]; //新建日期文件夾 $tmp_arr=explode('/',$ueditor_img); $datefloder='./Public/Upload/ueditor/image/'.$tmp_arr[5]; if(!is_dir($datefloder)) { mkdir($datefloder,0777); } $tmpimg='.'.$ueditor_img; $newimg=str_replace('/ueditor_temp/','/ueditor/',$tmpimg); //轉移圖片 if(rename($tmpimg, $newimg)) { $content=str_replace('/ueditor_temp/','/ueditor/',$content); } } }
下次編輯文章內容的時候使用同樣的思路,不過要先判斷是否是新上傳的圖片,原來的就不要動了。
還有一種情況是原來已經上傳的圖片在被編輯的時候刪除了,雖然數據庫修改了,但是文件還在,所以需要和原內容進行比較之后刪除。
//轉移ueditor文件
if(!empty($content))
{
//正則表達式匹配查找圖片路徑
$pattern='/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.jpeg|\.png]))[\'|\"].*?[\/]?>/i';
preg_match_all($pattern,$content,$res);
$num=count($res[1]);
for($i=0;$i<$num;$i++)
{
$ueditor_img=$res[1][$i];
//判斷是否是新上傳的圖片
$pos=stripos($ueditor_img,"/ueditor_temp/");
if($pos>0)
{
//新建日期文件夾
$tmp_arr=explode('/',$ueditor_img);
$datefloder='./Public/Upload/ueditor/image/'.$tmp_arr[5];
if(!is_dir($datefloder))
{
mkdir($datefloder,0777);
}
$tmpimg='.'.$ueditor_img;
$newimg=str_replace('/ueditor_temp/','/ueditor/',$tmpimg);
//轉移圖片
if(rename($tmpimg, $newimg))
{
$content=str_replace('/ueditor_temp/','/ueditor/',$content);
}
}else {
$imgarr[]=$ueditor_img;
}
}
}
//刪除在編輯時被刪除的原有圖片
if(!empty($_POST['oldcontent']))
{
//正則表達式匹配查找圖片路徑
$pattern='/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.jpeg|\.png]))[\'|\"].*?[\/]?>/i';
preg_match_all($pattern,$_POST['oldcontent'],$oldres);
$num=count($oldres[1]);
for($i=0;$i<$num;$i++)
{
$delimg=$oldres[1][$i];
if(!in_array($delimg, $imgarr))
{
$delimg='.'.$delimg;
unlink($delimg);
}
}
}
這樣問題就解決了,當然沒有用的圖片會都存在ueditor_temp文件夾里,不過是手動刪除還是做個小程序來刪除都是可以的。
希望對大家有幫助。