Laravel在上传新文件之前删除文件

问题描述 投票:0回答:2

按照本教程,我能够上传文件,但是当我上传另一个文件时,它将新文件添加到该文件夹​​中。我想先删除文件,然后用户才能上传新文件。

如果我确定文件在File Not Exist中,则为什么返回/uploads/images/nerison123_1581390807.PNG事件?>

// Get current user
$user = User::findOrFail(auth()->user()->id);
$image_path = $user->profile_image;

//delete the file first if it exists before uploading the new one
if (file_exists($image_path)) {
    @unlink($image_path);
} else {
    echo $image_path;
    echo "<br>";
    return "FILE NOT EXIST";
}

按照本教程,我能够上传文件,但是当我上传另一个文件时,它将新文件添加到该文件夹​​中。我想先删除文件,然后用户才能上传新文件。为什么会这样...

laravel
2个回答
1
投票

您可以使用public_path()image_path更改为完整路径:


0
投票
   $image = $request->file('image');
        $slug = str_slug($request->title);
        if (isset($image))
        {
            $currentDate = Carbon::now()->toDateString();
            $imagename = $slug.'-'.$currentDate.'-'. uniqid() .'.'. $image->getClientOriginalExtension();
            $image_resize = Image::make($image->getRealPath());   
            $image_resize->resize(1600,1066);
            if (!file_exists('storage/uploads/post'))
            {
                mkdir('storage/uploads/post',0777,true);
            }
            unlink('storage/uploads/post/'.$post->image);
            $image_resize->save('storage/uploads/post/'.$imagename);
        }else{
            $imagename = $post->image;
        }
© www.soinside.com 2019 - 2024. All rights reserved.