【问题标题】:Old File from storage is not being deleted on update Laravel更新 Laravel 时不会删除存储中的旧文件
【发布时间】:2020-08-22 13:30:30
【问题描述】:

我正在尝试在更新新图像时从存储中删除现有图像。 但是每次插入新图像时都会保留以前的图像。

当我从数据库中删除图像以取消链接时,我得到了完整的 url 即

http://127.0.0.1:8000/teacger-image/1598097262-85508.jpg

虽然只有teacher-image/1598097262-85508.jpg 已存储在数据库中。

图片删除功能

public function deleteImageFromStorage($value)
{
    if (!empty($value)) {
        File::delete('public/' . $value);
    }
}

当更新过程中有图像发布时,我已经在控制器中调用了该方法。

更新方法包括

 if ($request->hasFile('image')) {
            $teacher->deleteImageFromStorage($teacher->image);
            $file = $request->file('image');
            $filename =  time() . '-' . mt_rand(0, 100000) . '.' . $file->getClientOriginalExtension();
            $path = $file->storeAs('teacher-image', $filename);
            $teacher->image = $path;
        }

我也使用过Storage::delete()unlink,但它们似乎都不起作用。

帮助

【问题讨论】:

  • 能否提供更新方法的代码?
  • 我已经更新了代码 Adrian sir
  • 您是否将图像保存在公用文件夹中?
  • 我有 public/teacger-image 和那里的文件

标签: laravel file storage unlink


【解决方案1】:

这就是我在 Laravel 中删除文件的方式。

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ImagesController extends Controller
{
    public function deleteImageFromStorage($value)
    {
        if ( file_exists( storage_path($value) ) ) {
            Storage::delete($value);
        }
    }
}

确保使用 Illuminate\Support\Facades\Storage。

【讨论】:

  • 可以贴出原店方式吗?在我看来,db 条目不仅保存了路径,还保存了包括主机名在内的整个链接,如果您移植该站点,这将造成问题。你检查过存储在数据库中的值吗?
【解决方案2】:

尝试将您的 deleteImageFromStorage 方法更改为:

public function deleteImageFromStorage($value)
{
    if (!empty($value)) {
        File::delete(public_path($value));
    }
}

【讨论】:

  • 您已经在代码顶部添加了use File; 对吧?
  • 是的,使用 Illuminate\Support\Facades\File;这个
  • 尝试将其更改为仅文件,不使用 Illuminate\Support\Facades\
  • 没关系,但不工作。我不知道为什么我在 dd 检索到的图像时也得到127.0.0.1:8000。我很确定这一定是问题所在。尝试解析网址,但没有一个好主意。
  • 尝试 dd public_path($value) 是否显示正确的路径?尝试将其粘贴到浏览器中以查看图像
【解决方案3】:

我必须这样做才能解决我的问题。 该 url 被配置文件下 fi​​lesystems.php 上的配置设置获取。

public function deleteImageFromStorage($value)
{
    $path_explode = explode('/', (parse_url($value))['path']); //breaking the full url 
    $path_array = [];
    array_push($path_array, $path_explode[2], $path_explode[3]); // storing the value of path_explode 2 and 3 in path_array array
    $old_image = implode('/', $path_array);

    if ($old_image) {
        Storage::delete($old_image);
    }
}

如果将来有人遇到同样的问题,这可能会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 2021-12-01
    • 2016-11-30
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多