Cakephp 3 图片通过 API 上传到 Cloudinary

问题描述 投票:0回答:2

我正要将图像上传到 cloudinary - 图像 CDN 看起来 cloudinary.com,它支持所有语言和框架,包括 Cakephp 3,但对于 cakephp 3,我们没有包含在他们的站点中的步骤。谁能告诉我轻松上传图片的步骤?

image-uploading cakephp-3.0 cloudinary
2个回答
4
投票

根据他们的网站,我提供了上传程序。

基础文档:

http://cloudinary.com/documentation/php_integration#getting_started_guide

第一步: 安装

{
  "require": {
    "cloudinary/cloudinary_php": "dev-master"
  }
}

将以上内容添加到位于项目文件夹中的 composer.json 中。

您可以使用 composer 来更新它并获取依赖项。导航到项目文件夹后,在 composer 中运行以下命令。

php composer.phar update

第二步: 在 Cake PHP 中安装。

打开 AppController 并在 initialize 函数中添加以下内容

看起来像下面这样:

public function initialize() {
        parent::initialize();
        $this->loadComponent('Flash');

        \Cloudinary::config(array( 
        "cloud_name" => "sample", 
        "api_key" => "874837483274837", 
        "api_secret" => "a676b67565c6767a6767d6767f676fe1" 
       ));

}

在上面你可以找到cloudinary配置,替换成你自己的凭据。

要获取凭据,请点击下面的链接并登录,

https://cloudinary.com/users/login

第三步: 图片上传程序

<?php 

echo $this->Form->create('upload_form', ['enctype' => 'multipart/form-data']);
echo $this->Form->input('upload', ['type' => 'file']);
echo $this->Form->button('Change Image', ['class' => 'btn btn-primary']);
echo $this->Form->end(); 

?>

在你的视图文件中使用上面的代码。 (你可以根据需要修改)

在您的控制器中,您可以通过以下方式使用,

if (!empty($this->request->data['upload']['name'])) {
            $file = $this->request->data['upload']; //put the data into a var for easy use
            $cloudOptions = array("width" => 1200, "height" => 630, "crop" => "crop");
            $cloudinaryAPIReq = \Cloudinary\Uploader::upload($file["tmp_name"], $cloudOptions);
            $imageFileName = $cloudinaryAPIReq['url'];
        }

您可以将 $imagefilename 保存在您的数据库中,在这里完整的 url 被保存并重新填充。


0
投票

为此还有一个开源插件。兼容cakephp 4+, 这里:cakephp cloudinary 插件

安装:

composer require jovialcore/cake-cloudinary

config/app_local.php

中添加您的cloudinary凭据
    // ...
    'Cloudinary' => [
        'default' => [
            'cloud_name' => 'your_cloud_name',
            'api_key' => 'your_api_key',
            'api_secret' => 'your_api_secret',
            'secure' => true // use HTTPS
        ],
    ],
    // ...
];

要在控制器中使用 Cloudinary 组件,您需要在初始化方法中加载它:

// src/Controller/YourController.php

namespace App\Controller;

use Cake\Controller\Controller;
use Cake\Event\EventInterface;

class YourController extends Controller
{
    public function initialize(): void
    {
        parent::initialize();
        $this->loadComponent('CakeCloudinary.Cloudinary');
    }

    // ...
}

接下来,像这样上传资产:

$this->Cloudinary->upload($file, ['getUrl' => 'true']);

更多信息:这里:cakephp cloudinary 插件

© www.soinside.com 2019 - 2024. All rights reserved.