laravel中如何将上传的图片保存到Storage?

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

我正在使用图像干预将图像保存到存储文件夹。我有下面的代码,它似乎只是用空白图像保存文件名。我想我需要一种将文件内容写入文件夹的方法,但很难获取片段。

if ($request->hasFile('photo')) {
    $image = $request->file('photo');
    $fileName = time() . '.' . $image->getClientOriginalExtension();

    $img = Image::make($image->getRealPath());
    $img->resize(120, 120, function ($constraint) {
        $constraint->aspectRatio();                 
    });
                
    //dd();
    Storage::disk('local')->put('images/1/smalls'.'/'.$fileName, $img, 'public');
php laravel laravel-5
5个回答
20
投票

你需要做

if ($request->hasFile('photo')) {
    $image = $request->file('photo');
    $fileName = time() . '.' . $image->getClientOriginalExtension();
    
    $img = Image::make($image->getRealPath());
    $img->resize(120, 120, function ($constraint) {
        $constraint->aspectRatio();                 
    });
    
    $img->stream(); // <-- Key point
    
    //dd();
    Storage::disk('local')->put('images/1/smalls'.'/'.$fileName, $img, 'public');
}

3
投票
if ($request->hasFile('photo')) {
    // $path = Storage::disk('local')->put($request->file('photo')->getClientOriginalName(),$request->file('photo')->get());
    $path = $request->file('photo')->store('/images/1/smalls');
    $product->image_url = $path;
}

2
投票

简单的代码。

if($request->hasFile('image')){
    $object->image = $request->image->store('your_path/image');
}

谢谢。


1
投票

这是使用干预包以所需名称将图像保存在存储路径上的另一种方法。 (使用

Storage::putFileAs
方法)

public function store(Request $request)
{
    if ($request->hasFile('photo')) {

        $image      = $request->file('photo');
        $image_name = time() . '.' . $image->extension();

        $image = Image::make($request->file('photo'))
            ->resize(120, 120, function ($constraint) {
                $constraint->aspectRatio();
             });

        //here you can define any directory name whatever you want, if dir is not exist it will created automatically.
        Storage::putFileAs('public/images/1/smalls/' . $image_name, (string)$image->encode('png', 95), $image_name);
    }
}


0
投票

这在 Laravel 10 中对我有用

$folder = 'folder/';
$path = storage_path('app/public/'.$folder);
if ($request->hasFile('image')) {
    $image = ImageManager::imagick()->read($file);
    $image->save($path.$filename);
}
© www.soinside.com 2019 - 2024. All rights reserved.