如何解决使用 unlink() PHP 时出现“是目录”错误
我正在尝试一件简单的事情。
从 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()
外,所有代码似乎都按我的预期工作。
有好心人会帮助我吗?
解决方法
经过将近一天的努力想弄清楚发生了什么,此刻我在脑海中提交了这个问题来检查我在 $image
中的 foreach
变量,然后你猜怎么着?
有时它会变空。
嗯,发现问题了...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。