php 如何使用cloudinary + Laravel上传图片?

bn31dyow  于 12个月前  发布在  PHP
关注(0)|答案(2)|浏览(113)

好吧,发生了什么事是,我想通过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
然后我试着检查记录是否被创建,但它没有被创建。
我能做什么,有人知道吗?
谢谢

bmp9r5qi

bmp9r5qi1#

好吧,我解决了:)

//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;

字符串
但如果有人有最好的办法,请告诉我

r1wp621o

r1wp621o2#

这就是我在Laravel 10中所做的。
我创建了一个可重用的客户端CloudinaryImageClient.php

<?php

namespace App\Integrations\files;

use Cloudinary\Api\Upload\UploadApi;
use Cloudinary\Configuration\Configuration;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;

class CloudinaryImageClient
{
    
    protected $cloudinaryInstance;
    
    public function __construct()
    {
        $this->cloudinaryInstance = Configuration::instance([
            'cloud' => [
                'cloud_name' => Config::get('cloudinary.cloud_name'),
                'api_key' => Config::get('cloudinary.api_key'),
                'api_secret' => Config::get('cloudinary.api_secret')
            ],
            'url' => [
                'secure' => true
            ]]);
    }

    public function uploadImage(string $mimeType, string $base64FileContents): CloudinaryResults
    {

        $formattedUploadUri = self::createUri($mimeType, $base64FileContents);

        try {
            $uploadClient = new UploadApi();
            $results = $uploadClient->upload($formattedUploadUri, ['resource_type' => 'image']);

            Log::info("cloudinary upload results: " . json_encode($results));
            return CloudinaryResults::success($results['secure_url'], $results['url']);

        } catch (\Exception $e) {
            Log::error("Failed to upload file to cloudflare $e");
            return CloudinaryResults::failed($e->getMessage());
        }
    }

    /**
     * Utility function
     *
     * @param string $mimeType -- example image/jpeg
     * @param string $base64FileContents
     * @return string uploadUri in format 'data:image/jpeg;base64, LzlqLzRBQ...  {Base64 image data}'
     */
    private static function createUri(string $mimeType, string $base64FileContents): string
    {
        return 'data:' . $mimeType . ';base64,' . $base64FileContents;
    }

}

字符串
下面是我如何在一个控制器上使用定制的可重用客户端

class CustomerBooksController extends Controller
{

    public function __construct()
    {

    }

    public function uploadImage(Request $request): JsonResponse
    {
        $request->validate([
            'image_file' => 'required|file',
        ]);

        $cloudinaryClient = new CloudinaryImageClient();
        $mimeType = $request->file('image_file')->getClientMimeType();
        $base64Contents = base64_encode($request->file('image_file')->getContent());

        $results = $cloudinaryClient->uploadImage($mimeType,$base64Contents);

        return response()->json($results);
    }

}

CloudinaryResults.php

<?php

namespace App\Integrations\files;

class CloudinaryResults
{
    
    public bool $isSuccess;
    public string $insecureUrl;
    public string $secureUrl;
    public string $msg;

    public static function success(string $secureUrl, string $insecureUrl): CloudinaryResults
    {
        $results = new CloudinaryResults();
        $results->isSuccess = true;
        $results->secureUrl = $secureUrl;
        $results->insecureUrl = $insecureUrl;
        return $results;
    }

    public static function failed(string $msg): CloudinaryResults
    {
        $results = new CloudinaryResults();
        $results->isSuccess = false;
        $results->msg = $msg;
        return $results;
    }
    
}

  • Cloudinary版本-“cloudinary/cloudinary_php”:“^2.10”
  • Laravel Framework 10.9.0

相关问题