【问题标题】:LARAVEL How to delete image from public folder?LARAVEL 如何从公共文件夹中删除图像?
【发布时间】:2020-04-11 18:28:59
【问题描述】:

我正在编写一篇博文,当我点击添加帖子时,任何文件夹中的图像都会被放入 public/user/img/ 当我删除整个表格行时如何删除它? (点击删除帖子),请看下面的公共函数deletePost($id),我可以连续删除详细信息(文本)但不能删除文件夹中的文件。 请帮忙

public function deletePost($id){
    $posts = Post::where('id',$id);
    $posts->delete();
    return back()->with('delete_posts_success','Deleted!');
}

public function getAddPost() {
    return view('admin.publish');
}

public function postAddPost(Request $request) {
    $post = $request->all();


    $post = new Post;
    $post->title = $request->title;
    $post->author = $request->author;
    $post->content = $request->content;
    $post->intro = $request->intro;
    $post->type = $request->type;

    if($request->hasFile('image')) {
        $file = $request->file('image');
        $extension = $file->getClientOriginalExtension();
        if($extension != 'jpg' && $extension != 'png' && $extension != 'jpeg') {
            return back()->with('Error', 'File extension must be jpg, png, jpeg');
        }
        $imageName = $file->getClientOriginalName();
        $file->move("user/img", $imageName);
        $post->image = $imageName;
    } else {
        $imageName = null; 
    }


    $post->save();
    return back()->with('create_posts_success','Published!');
}

【问题讨论】:

标签: php laravel controller sql-delete delete-file


【解决方案1】:

您必须将文件名保存在数据库中的某个位置才能上传此帖子

现在,当您删除该帖子时, -> 从你的数据库记录中获取文件名, -> 使用file_exists() 检查文件是否存在于该位置 -> 使用unlink()删除找到的文件

-> 获取文件删除响应(true|false)

在你的情况下,它变成如下所示

$filePathName = 'user/img/' . $post->image;
if( file_exists($filePathName) ){
   unlink($filePathName);
}

请忽略我的语法错误 完成

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 2014-03-24
    • 2017-02-03
    • 1970-01-01
    • 2019-09-05
    • 2021-01-26
    • 2018-03-24
    • 1970-01-01
    • 2016-02-23
    相关资源
    最近更新 更多