简体   繁体   English

如何将上传的图像保存到 Laravel 中的 Storage?

[英]How to save uploaded image to Storage in laravel?

I am using Image intervention to save an image to the storage folder.我正在使用图像干预将图像保存到存储文件夹。 I have the code below and it seems to just save a file name with a blank image.我有下面的代码,它似乎只是用空白图像保存文件名。 I think I need a way for the file contents to be written to the folder but struggling for the snippet.我想我需要一种将文件内容写入文件夹的方法,但正在为代码片段而苦苦挣扎。

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');

You need to do你需要做

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');
}
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;
        }

Here is another way to save images using intervention package on storage path with desired name.这是另一种使用所需名称在存储路径上使用干预包保存图像的方法。 (using Storage::putFileAs method ) (使用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);
    }
}

Simple Code.简单的代码。

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

Thanks.谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM