我正在尝试一个简单的事情。从 post 方法获取图像,将这些图像移动到我的 public/images 文件夹中,如果出现任何阻止代码继续运行的错误(比如我检查的不受支持的文件类型preg_match()
),则回滚整个事情,换句话说, 删除已经移动到文件夹中的文件。
问题是,当我尝试使用时,unlink()
我得到了这个“是目录”错误。我不是要删除目录!我正在尝试删除文件!
我使用is_file()
, is_dir()
,file_exists()
来检查所有内容,所有内容都指向一个文件。我几乎整天都在试图弄清楚发生了什么,但没有成功。我几乎要放弃这件事了。
我在 Ubuntu 20.04 上,使用 Lumen 8 和 PHP 7.4。这是我的控制器代码:
<?php
namespace App\Http\Controllers;
use App\Models\Insumo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class InsumosController extends BaseController
{
public function __construct()
{
$this->classe = Insumo::class;
}
public function store(Request $request)
{
try {
DB::beginTransaction();
$images = [
'mainImg' => "",
'img1' => "",
'img2' => "",
'img3' => "",
'img4' => ""
];
$filesKeys = $request->files->keys();
foreach ($filesKeys as $fileKey) {
$pattern = "/^image\/(jpeg|jpg|bmp|png|gif)$/";
$mimeType = $request->file($fileKey)->getMimeType();
if (!preg_match($pattern, $mimeType)) {
throw new \Exception('Not supported file', 415);
}
$insumoNome = lcfirst(str_replace(' ', '', $request->nome));
$ext = "." . $request->file($fileKey)->extension();
$newName = $insumoNome . "-" . $fileKey . "-" . bin2hex(random_bytes(5)) . $ext;
$images[$fileKey] = $newName;
$request->file($fileKey)->move('images', $newName);
}
$insumo = Insumo::create([
'nome' => $request->nome,
'descricao' => $request->descricao,
'mainImg' => $images['mainImg'],
'img1' => $images['img1'],
'img2' => $images['img2'],
'img3' => $images['img3'],
'img4' => $images['img4'],
]);
DB::commit();
return response()->json($insumo, 201);
} catch (\Exception $e) {
DB::rollBack();
$imagesDir = __DIR__ . '/../../../public/images/';
foreach ($images as $image) {
if (file_exists($imagesDir . $image)) {
$imagesPath = $imagesDir . $image;
unlink($imagesPath);
}
}
return response()->json($e->getMessage(), $e->getCode());
}
}
}
除了unlink()
. 会有好心人帮我解决这个问题吗?