使用 php (yii2) 从本地计算机上传图像到 cloudinary 服务器

upload image from local computer to cloudinary server using php (yii2)

我正在使用 yii2 框架让网站通过 API 上传到 Cloudinary。 但出于某种原因,API 函数需要文件路径才能进行上传。

web 文件夹中的文件可以上传,但我不想上传到我的服务器而不是将它发送到 cloudinary 服务器(操作太多),我想从我的本地主机直接上传到 cloudinary 服务器

来自 yii2 控制器的上传代码:

    public function actionCreate()
    {
        $model = new Galerias();

        // inicializar o cloudinary
        $config = Configuration::instance();
        $config->cloud->cloudName = 'cloudName';
        $config->cloud->apiKey = 'yayaiknow';
        $config->cloud->apiSecret = 'gogogodude';
        $config->url->secure = true;

        // esta a ser feito o upload
        if ($model->load(Yii::$app->request->post())) {
            $data2 = date('Y-m-d h:m:s');
            if($model->validate()) {
                $image = UploadedFile::getInstance($model, 'image');
                // maybe remove this if to get URL of image from callback
                if((new UploadApi())->upload($image)){
                    $data = date('Y-m-d h:m:s');
                    $model->created_at = $data;
                    $model->updated_at = null;
                    if($model->save()){
                        return $this->redirect(['view', 'id' => $model->id]);
                    }
                }
            }
        }

        return $this->render('create', [
            'model' => $model,
        ]);

    }

表格代码:

<div class="galerias-form">
    <p>Imagem (tipo PNG-8) para: </p>
    <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

    <?= $form->field($model, 'image')->fileInput()->label('Monitores "Dimensão recomendado: 1920x1080px"'); ?>

    <?= $form->field($model, 'descricao')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'local')->radioList(array(0=>'Destaque',1=>'Fundo')); ?>

    <div class="form-group">
        <?= Html::submitButton('Guardar', ['class' => 'btn btn-success']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

当我尝试上传时(砰的一声)我收到了这个错误:

Cloudinary\Api\Exception\BadRequest
Unsupported source URL: a.jpg

我试图获取文件的原始相对(或绝对)路径,但没有成功。

一个有效的解决方案是将文件上传到我的网站服务器,到达那里并将其发送到 Cloudinary 服务器,最后从网站服务器中删除该图像。 (步骤太多)

我需要帮助使其变得简单,上传文件并将其发送到 Cloudinary 并在回调中获取 URL 位置并将其保存在数据库中。

链接:

https://cloudinary.com/documentation/php_image_and_video_upload

https://www.yiiframework.com/doc/guide/2.0/en/input-file-upload

您应该传递您正在传递 Cloudinary 上传未知的 UploadedFiles 对象的文件路径 api。

您应该通过 $image->tempName 将路径传递到 (new UploadApi())->upload(),如下所示

(new UploadApi())->upload($image->tempName)

还有方法returns文件上传的响应,示例如下

Array
(
  [public_id] => c87hg9xfxrd4itiim3t0
  [version] => 1571218607
  [signature] => f8645b000be7d717599affc89a068157e4748276
  [width] => 864
  [height] => 576
  [format] => jpg
  [resource_type] => image
  [created_at] => 2017-06-23T13:59:18Z
  [bytes] => 120253
  [type] => upload
  [url] => http://res.cloudinary.com/demo/image/upload/v1571218607/c87hg9xfxrd4itiim3t0.jpg
  [secure_url] => https://res.cloudinary.com/demo/image/upload/v1571218607/c87hg9xfxrd4itiim3t0.jpg
)

或者出错时抛出异常,你应该改用 try catch 块。

try{
    (new UploadApi())->upload($image->tempName);
}catch(\Exception $e){
   Yii::$app->session->setflash('error',$e->getMessage());
}

你的完整动作应该是这样的

public function actionCreate()
{
    $model = new Galerias();

    // inicializar o cloudinary
    $config = Configuration::instance();
    $config->cloud->cloudName = 'cloudName';
    $config->cloud->apiKey = 'yayaiknow';
    $config->cloud->apiSecret = 'gogogodude';
    $config->url->secure = true;

    // esta a ser feito o upload
    if ($model->load(Yii::$app->request->post())) {
        $data2 = date('Y-m-d h:m:s');
        if ($model->validate()) {
            $image = UploadedFile::getInstance($model, 'image');
            // maybe remove this if to get URL of image from callback
            try {
                $response = (new UploadApi())->upload($image->tempName);
                $data = date('Y-m-d h:m:s');
                $model->created_at = $data;
                $model->updated_at = null;
                if ($model->save()) {
                    return $this->redirect(['view', 'id' => $model->id]);
                }
            } catch (\Exception $e) {
                Yii::$app->session->setFlash('error', $e->getMessage());
            }
        }
    }

    return $this->render('create', [
        'model' => $model,
    ]);

}