【问题标题】:How Upload images with cloudinary + Laravel?如何使用 cloudinary + Laravel 上传图片?
【发布时间】:2021-09-29 07:38:11
【问题描述】:

好吧,我想通过 Laravel 将图像上传到 Cloudinary, 我按照文档中所述的步骤进行操作:

https://github.com/cloudinary-labs/cloudinary-laravel 在这里:https://cloudinary.com/blog/laravel_file_upload_to_a_local_server_or_to_the_cloud

我正在使用 Laravel 8,这是我的代码:

 public function store(Request $request){

    $request->validate([
        'name' => 'required|string|unique:festivals|max:255', //unique:table
        'description' => 'required|string|max:255',
        'image' => 'required|image|dimensions:min_width=200,min_height=200',
    ], self::$messages);

    //Here I create an instance and upload file to server 
    $festival = new Festival($request->all());
    $path = cloudinary()->upload($request->file('image')->getRealPath())->getSecurePath();
    dd($path);

    //Then at field image of festivals que save the path and that goes to the database
    $festival->image = 'festivals/' . basename($path);
    $festival->save();


    return response() -> json($festival, 201); //code 201 created

}

当我尝试通过 Postman 创建新记录时,会发生这种情况:

Error after register new festival

但是,图片已上传到 Cloudinary:

image uploaded

然后我尝试检查记录是否已创建,但没有创建。

我能做什么,有人知道吗?

谢谢

【问题讨论】:

    标签: php laravel cloudinary


    【解决方案1】:

    好的,我解决了:)

        //Here I create an instance and upload file to server
        $festival = new Festival($request->all());
        $result = $request->image->storeOnCloudinary();
         
        //Here I get the url
        $path = $result->getPath();
    
        //Then at field image of festivals que save the path and that goes to the database
    
        //$festival->image = $path; output: "https://res.cloudinary.com/test/image/upload/v1226931211/zuiyb17vfs8dre6gvuov.jpg"
        //$festival->image = dirname($path); output: "https://res.cloudinary.com/test/image/upload/v1526711711"
        //$festival->image = basename($path); output: "zuiy31lvfs4dre5gvuov.jpg"
        $base =  basename(dirname($path).basename($path)); //output: "v1636941221zuiyb14vfsmdre6gvuov.jpg"
        $folder =  substr($base, 0, -24); //output: "v1626915261"
        //So:
        $img_path = $folder.'/'.basename($path);
    
        $festival->image = 'festivals/'.$img_path;  //imageFolder/imageName.jpg;
    

    但是如果有人有最好的方法,请告诉我

    【讨论】:

      猜你喜欢
      • 2019-05-07
      • 2022-12-16
      • 2016-09-20
      • 2018-06-04
      • 2019-03-17
      • 2019-05-30
      • 2020-09-20
      • 2016-09-10
      • 2021-01-03
      相关资源
      最近更新 更多