admin_create.tpl
,我們在「上傳相片或影片」的欄位下方將圖片讀出,並加上刪除的多選框:
<div class="mb-3 row">
<label for="media" class="col-sm-3 col-form-label">上傳相片或影片</label>
<div class="col-sm-9">
<input type="file" class="form-control" id="media" name="media[]" multiple accept=".png, .jpg, .gif, .mp4">
<div class="row">
{if isset($news.files)}
{foreach $news.files as $filename=> $file_path}
<div class="col-lg-3">
<img src="{$file_path}" class="img-thumbnail" style="object-fit: cover; height: 150px;">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="del[]" value="{$file_path}" id="{$filename}">
<label class="form-check-label" for="{$filename}">
刪除此圖檔
</label>
</div>
</div>
{/foreach}
{/if}
</div>
</div>
</div>
isset()
判斷有無附檔,若有再用 foreach
讀出checkbox
欄位,其 name
必須加上 []
,表示可以複選$del[]
變數給 admin.php
,所以接著請在 admin.php
先加入 $del
陣列的所有檔名過濾
// 變數過濾
$id = isset($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0;
$op = isset($_REQUEST['op']) ? htmlspecialchars($_REQUEST['op']) : 'create';
$del = isset($_REQUEST['del']) ? array_map('htmlspecialchars', $_REQUEST['del']) : [];
然後將 $del
加入 update()
成為第二個參數,也就是更新時,若有欲刪除的檔案,也一併刪除。
// 更新文章
case 'update':
update($id, $del);
header("location: index.php?op=show&id=$id");
exit;
由於檔案是由 uploads()
處理,所以,也將 $del
傳入 uploads()
中處理。
// 更新文章
function update($id, $del=[])
{
global $pdo;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 取得表單值
...略...
$media = uploads($id, $del);
try {
// 準備SQL語句
...略...
} catch (PDOException $e) {
echo "更新失敗:" . $e->getMessage();
}
}
return $id;
}
uploads()
,一樣加入第二參數 $del
,並在讀出現有檔案陣列 $news['files']
後,判斷有無 $del
$del
中$news['files']
陣列中用 unset()
移除該檔案資料
// 處理多檔案上傳
function uploads($id, $del=[])
{
global $uploadDir;
if (!empty($_FILES['media'])) {
// 建立存放圖檔的目錄
...略...
// 取出原有的檔案資料陣列
$news = show($id);
// 刪除指定的檔案
if (!empty($del)) {
foreach ($news['files'] as $name => $fileName) {
if (in_array($fileName, $del)) {
if (unlink($fileName) or !file_exists($fileName)) {
unset($news['files'][$name]);
}
}
}
}
$allFiles = $fileData ? array_merge($news['files'], $fileData) : $news['files'];
// 將檔案相關資訊轉換為JSON格式
$media = !empty($allFiles) ? json_encode($allFiles, 256) : '[]';
return $media;
}
}
此外,若是在修改狀態