繁体   English   中英

文件存在但 laravel 找不到它 (FileNotFoundException)

[英]File exist but laravel can't find it (FileNotFoundException)

我正在尝试检查文件是否存在,以便在删除帖子时将其删除,但从未找到它。

如果我将Storage::exists()更改为Storage::get()只是为了检查,我会得到路径为 C:/xampp/htdocs/cms/blog/public/images/apple.jpg 的文件未找到异常我把图片放到浏览器里就可以看到了。

将 function 存储在 PostController 上

public function store(CreatePostRequest $request)
{
    $input = $request->all();

    if ($file = $request->file('file')) {
        //
        $name = $file->getClientOriginalName();
        $file->move(public_path('images/'), $name);
        $input['path'] = $name;
    }

    $new_post = Post::create($input);
    return redirect(route('post.show', $new_post->id));
}

在 PostController 上销毁 function

public function destroy($id)
{
    $post = Post::findOrFail($id);

    if (Storage::exists(public_path('images/') . $post->path))
        Storage::delete(public_path('images/') . $post->path);

    $post->delete();

    return redirect(route('posts.index'));
}

我的文件系统上也有这个。php

'links' => [
    public_path('storage') => storage_path('app/public'),
    public_path('images') => storage_path('app/images'),
],

我可以使用src="{{'/images/'. $post->path}}"轻松地在 blade 中显示图像

您可以尝试使用unlink

$image_path = $post->path;
unlink($image_path);

第二种选择是使用File Facade。

use Illuminate\Support\Facades\File; 
$filename = $post->path;
File::delete($filename);

确保图像路径正确。

我不得不使用 Aless 推荐的Illuminate\Support\Facades\File

修复了 PostController 上的销毁功能

public function destroy($id)
{
    $post = Post::findOrFail($id);

    $imagePath = public_path('images/') . $post->path;

    if (File::isFile($imagePath))
        File::delete($imagePath);

    $post->delete();

    return redirect(route('posts.index'));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM