【问题标题】:How to upload an image using Laravel?如何使用 Laravel 上传图片?
【发布时间】:2019-05-30 07:09:04
【问题描述】:

问题:
我想使用 Laravel 将图像上传到 mySQL 数据库。

我尝试过的:
我查找了其他堆栈溢出问题,但没有帮助。

我期待的结果:
是将图像名称或路径保存到数据库表中的列中,以便稍后检索并显示为博客中的帖子。

【问题讨论】:

标签: laravel image file path upload


【解决方案1】:

首先,您需要在视图中显示表单(不要忘记 csrf 令牌):

<form action="/image-upload" method="POST" enctype="multipart/form-data">
    @csrf
    <input type="file" name="image">
    <button type="submit">Upload</button>
</form>

然后在你的路由文件中添加 POST 方法的路由:

Route::post('image-upload', 'ImageUploadController@imageUploadPost');

然后在您的控制器上创建将验证您的图像并将其移动到“public/images”文件夹的函数。

public function imageUploadPost()
{
    request()->validate([
        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);

    $imageName = time().'.'.request()->image->getClientOriginalExtension();
    request()->image->move(public_path('images'), $imageName);
}

如需更好的解决方案,请阅读:Laravel File Storage

【讨论】:

    【解决方案2】:

    实际上使用 Laravel 只需要几行代码。假设您有一个用户,他的头像存储在数据库中。以下是从数据库中存储和检索头像的方法:

    1. 首先,您需要在 users 表中有一个 avatar 列,该列可以存储二进制数据。根据您希望头像图像的大小,列的数据类型可以是以下之一:

    BLOB 高达 64KB

    MEDIUMBLOB 高达 16MB

    LONGBLOB 高达 4GB

    2.要将上传的图像存储在数据库中,您可以这样做:

    Route::post('user/{id}', function (Request $request, $id) {
        // Get the file from the request
        $file = $request->file('image');
    
        // Get the contents of the file
        $contents = $file->openFile()->fread($file->getSize());
    
        // Store the contents to the database
        $user = App\User::find($id);
        $user->avatar = $contents;
        $user->save();
    });
    

    3.要获取和输出头像,您可以执行以下操作:

    Route::get('user/{id}/avatar', function ($id) {
        // Find the user
        $user = App\User::find(1);
    
        // Return the image in the response with the correct MIME type
        return response()->make($user->avatar, 200, array(
            'Content-Type' => (new finfo(FILEINFO_MIME))->buffer($user->avatar)
        ));
    });
    

    注意:请记住这一点,MySQL 不是存储 BLOB 的合适解决方案。您可能需要使用像 Amazon S3 这样的对象存储服务。

    【讨论】:

      【解决方案3】:

      用这个上传图片

         /**
           * Store a newly created resource in storage.
           *
           * @param  \Illuminate\Http\Request  $request
           * @return \Illuminate\Http\Response
           */
          public function store(Request $request)
          {
             // $this->validate($request,[//'movie_name'=>'required',
             //     // 'description'=>'required',
             //      //'video_url'=>'required',
             //      'image'=>'required|mimes:jpeg,jpg,png,gif|required|max:10000',
             //  ]);
      
         if ($request->hasFile('image') && $request->hasFile('image2')) {
           $file = $request->file('image');
           //$image=$file->getClientOriginalName();
           $image = time().'.'.$file->getClientOriginalExtension();
           $destinationPath ='assets/admin/uploads/image/';
           $file->move($destinationPath,$image);
           //echo  $destinationPath;exit();
              //echo  $image."<br/>";
          $file2 = $request->file('image2');
          $bg_images = time().'.'.$file2->getClientOriginalExtension();
          //$bg_images=$file2->getClientOriginalName();
          $destinationPath ='assets/admin/uploads/bg_images/';
          $file2->move($destinationPath,$bg_images);
           $insert_data=array('movie_name'=>$request->movie_name,
                  'description'=>$request->description,
                  'video_url'=>$request->video_url,
                  'image'=>$image,
                  'bg_images'=>$bg_images,
                  'created_at'=>now(),
                  'updated_at'=>now()
              );
              //print_r($insert_data);exit();
          }
          else
          {
              if ( $request->hasFile('image2')) {
               $file2 = $request->file('image2');
               $bg_images = time().'.'.$file2->getClientOriginalExtension();
              //$bg_images=$file2->getClientOriginalName();
               $destinationPath ='assets/admin/uploads/bg_images/';
               $file2->move($destinationPath,$bg_images);
               //echo  $destinationPath;exit();
                  //echo $bg_images;
                   $insert_data=array('movie_name'=>$request->movie_name,
                      'description'=>$request->description,
                      'video_url'=>$request->video_url,
                      //'image'=>$image,
                      'bg_images'=>$bg_images,
                      'created_at'=>now(),
                      'updated_at'=>now()
                  );
              //print_r($insert_data);exit();
              }
              if ($request->hasFile('image') ) {
               $file = $request->file('image');
               //$image=$file->getClientOriginalName();
               $image = time().'.'.$file->getClientOriginalExtension();
               $destinationPath ='assets/admin/uploads/image/';
               $file->move($destinationPath,$image);
               //echo  $destinationPath;exit();
                  //echo  $image."<br/>";
                $insert_data=array('movie_name'=>$request->movie_name,
                      'description'=>$request->description,
                      'video_url'=>$request->video_url,
                      'image'=>$image,
                      //'bg_images'=>$bg_images,
                      'created_at'=>now(),
                      'updated_at'=>now()
                  );
                 // print_r($insert_data);exit();
              }
              if ( ! $request->hasFile('image2') && ! $request->hasFile('image') ) {
                 $insert_data=array('movie_name'=>$request->movie_name,
                          'description'=>$request->description,
                          'video_url'=>$request->video_url,
                          //'image'=>$image,
                         // 'bg_images'=>$bg_images,
                          'updated_at'=>now()
                          );
                 // print_r($update_data);exit();
              }
          }    
          //exit();
      
          // echo $image;
          //exit();
      
          //print_r($insert_data);exit();
          $insert=DB::table('movies')->insert($insert_data);
          if ($insert) {
              return redirect()->route('admin.list_movies')->withSuccess('Record saved');
          }
          else {
              return redirect()->route('admin.list_movies')->withError('Record not saved');
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-09-29
        • 2018-08-11
        • 2020-03-25
        • 2016-08-16
        • 2020-07-04
        • 2014-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多