【问题标题】:How to save images in laravel?如何在 laravel 中保存图片?
【发布时间】:2019-06-20 06:15:33
【问题描述】:

我从用户表单中获取图像。我需要调整图像大小并将其保存到public/images。 图片的链接必须保存到数据库中。现在我有一个存储在数据库中的/tmp/phpNgculU 文件的临时存储空间。因此,我无法在浏览器中显示图像。帮助我更改我的代码。我真的不明白我的错误在哪里。 这需要在没有php artisan storage:link的情况下完成

这是我的控制器的“更新”方法的一部分:

if(!empty($request->file())) {
    $task->images = $request->file('file');
    $img = Image::make($task->images)->resize(320, 240, function ($constraint) {
        $constraint->aspectRatio();
    });
    $imgName = rand(11111, 99999).'.'.$task->images- >getClientOriginalExtension();
    $img->storeAs('images/', $imgName);
}

我也得到错误:

命令 (StoreAs) 不适用于驱动程序 (Gd)。

【问题讨论】:

    标签: laravel image


    【解决方案1】:

    你可以这样做:

    如果你想存储上传图片的路径,你需要一个数据库表。

    Schema::create('images', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->string('path');
                $table->timestamps();
            });
    

    还有Image 模型:

    <?php
    namespace App;
    use Illuminate\Database\Eloquent\Model;
    class Image extends Model
    {
        protected $table = 'images';
        protected $fillable = [
          'path',
          'name',
        ];
    }
    

    app\Repositories 目录上创建一个repository(可能您也需要创建该目录):

    namespace App\Repositories;
    
    use Illuminate\Support\Facades\Storage;
    use Symfony\Component\HttpFoundation\Response;
    
    class ImageRepository
    {
        /**
         * Upload the image
         * @param $image
         * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
         */
        public function uploadImage($image, $name=null)
        {
            return $this->upload($image);
        }
        /**
         * Upload the image
         *
         * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
         */
        private function upload($image, $name=null)
        {
            try{
                $name == null ? $name = uniqid() : $name = $name;
                $path = Storage::disk('public')->put('images', $image);
                $uploadedImage = Image::create([
                    'path' => $path,
                    'name' => $name,
                ]);
                return $uploadedImage;
            }catch (\Exception $exception){
                return response('Internal Server Error', Response::HTTP_INTERNAL_SERVER_ERROR);
            }
        }
    }
    

    您的控制器代码:

    //Create a variable to the image repository:
    private $imageRepository;
    
    public function __construct(ImageRepository $imageRepository)
    {
        $this->imageRepository = $imageRepository;
    }
    
    //In your update function:
    public function update(Request $request)
    {
        $image = Input::file('file'); //i think you call your input on the html form as 'file'
        $img = Image::make($image)->resize(320, 240, function ($constraint) {
            $constraint->aspectRatio();
        });
        $imgName = rand(11111, 99999).'.'.$image->getClientOriginalExtension();
        $this->imageRepository->uploadImage($img, $imgName);
    
        //Continue your logic here
    }
    

    记住:您需要在 HTML 表单中添加enctype

    enctype="multipart/form-data"

    希望对你有帮助。

    【讨论】:

    • 很高兴为您提供帮助:)
    【解决方案2】:

    你可以使用 Laravel File Storage

    HTML 表单

     <form method="post" action="/upload" enctype="multipart/form-data">
            {{ csrf_field() }}
            <input type="file" name="image">
            <button type="submit">Submit</button>
        </form>
    

    图像方法助手

    public static function saveImage($image, $path, $option){
        try {
            if($image != null) {
                $image_path = $image->store($path, $option);
                return $image_path;
            } else {
                return null;
            }
        } catch (\Exception $e) {
            echo 'Image Helper saveImage ' .$e->getMessage();
            }
        }
    
    

    控制器

    public function store(Request $request){
            $category = new Category;
            $category->name = $request->name;
                if($request->has('image')){
                    $category->image_path = saveImage($request->file('image'),'category', 'public');
                }
            $category->save();
            return $category
        }
    
    

    【讨论】:

      猜你喜欢
      • 2022-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      相关资源
      最近更新 更多