【问题标题】:How to delete older image from public folder on upload using Laravel如何在使用 Laravel 上传时从公用文件夹中删除旧图像
【发布时间】:2019-11-26 00:17:21
【问题描述】:

我的公用文件夹 profile_images 中有一个文件夹,其中存储了我的图像。上传新图像时,我想从该文件夹中删除旧图像。

如何在上传时删除旧文件?

这是我的整个控制器代码:

public function uploadImage(Request $request)
{
    $user_id = $request->input('user_id');
    $image = $request->input('image');
    $r = [
        'user_id' => $user_id,

    ];
    $validator = Validator::make($r, [
        'user_id' => 'required|exists:users,id',

    ]);
    if($validator->fails()) {
        return response(['status' => false, 'message' => 'Validation Errors', 'errors' => $validator->errors()->all()], 500);
    }

    if ($validator->fails()) {
        return response([
            'status' => false,
            'message' => __('messages.validation_errors'),
            'errors' => $validator->errors()->all()], 200);
    }
    try {
        $path = public_path('profile_images');
        @mkdir($path, '0777', true);

        $image = base64_decode($image);

        $imageName = str_random(10).'.'.'png';
        Storage::disk('profile-image')->put($imageName, $image);

        $path = asset('public/profile_images/' . $imageName);

        $this->userBasicInfo->where('user_id', $user_id)->update(['profile_pic' => $path]);

        return response(['status' => true, 'message' => 'Image Uploaded successfully', 'data' => ['profile_image' => $path]], 200);

    } catch (\Exception $ex) {
        return response(['status' => false, 'message' => $ex->getMessage()], 500);

    }
}

【问题讨论】:

  • 我会看看unlink,但不确定这是否正是您要找的。​​span>
  • 我也尝试使用 unlink 但不起作用它说 unlink(): http 不允许取消链接
  • 任何其他更好的解决方案
  • 如果要使用unlink 删除某些内容,则需要使用文件路径。因此,请确保您使用的是 public/profile_images/whatevertheimageis.png 之类的路径。

标签: php laravel image file delete-file


【解决方案1】:

Laravel 有删除文件的方法:

Storage::delete('profile-image/old_file.jpg');

另外,您应该记住旧文件名以便将来删除它:

$imageName = str_random(10).'.'.'png';

将此 imageName 保存在某处或使用您的 user_id 来了解您要删除的图像。

【讨论】:

  • 我会手动添加文件名吗?就像你说的('profile-image/78777.jpg)?
  • 如果你想保存用户头像,你可以用这个用户的id保存这张图片。
【解决方案2】:

删除公共目录中任何文件的默认方法

File::delete(public_path('file path and name'));

【讨论】:

    猜你喜欢
    • 2019-11-25
    • 1970-01-01
    • 2022-01-15
    • 2016-02-23
    • 2014-12-04
    • 2021-04-27
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    相关资源
    最近更新 更多