【问题标题】:File Upload CakePHP 3.4文件上传 CakePHP 3.4
【发布时间】:2017-08-03 07:14:14
【问题描述】:

我试图从表单上传一个简单的文件以保存在我的 webroot/img 文件夹中,但是我遇到了一些困难。

这是视图中的表单:

<?= $this->Form->create($productImage) ?>
<fieldset>
    <legend><?= __('Add Product Image') ?></legend>
    <?php
        echo $this->Form->control('product_id', ['options' => $products]);
        echo $this->Form->file('image', ['label' =>'','size'=>'50']); //Uploaded file
        echo $this->Form->control('image_path');
    ?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>

这是控制器中的功能:

    public function add()
{
    $productImage = $this->ProductImages->newEntity();
    if ($this->request->is('post')) {
        $image = $this->request->data['image'];
        if (move_uploaded_file($image,WWW_ROOT . '/img')) {
            $this->Flash->success(__('file upload successful'));
        } else {
            $this->Flash->success(__('file upload unsuccessful'));
        }
        $productImage = $this->ProductImages->patchEntity($productImage, $this->request->getData());

        if ($this->ProductImages->save($productImage)) {
            $this->Flash->success(__('The product image has been saved.'));

            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('The product image could not be saved. Please, try again.'));
    }
    $products = $this->ProductImages->Products->find('list', ['limit' => 200]);
    $this->set(compact('productImage', 'products'));
    $this->set('_serialize', ['productImage']);
}

move_uploaded_file 一直返回 false,我不知道为什么。

非常感谢您的帮助。

山姆。

【问题讨论】:

  • 请在您的调试模式下检查可能的错误

标签: php cakephp file-upload cakephp-3.4


【解决方案1】:

你必须关心两件事

1.正确的声明

在您的 html 表单中添加 enctype="multipart/form-data" (['type' =&gt; 'file']) 在 CakePHP 表单中创建。那么你的代码将是

&lt;?= $this-&gt;Form-&gt;create($productImage,['type' =&gt; 'file']) ?&gt;
详情Here

2。上传图片

以正确的方式上传图片 使用
$this-&gt;request-&gt;data['image']['name'];

【讨论】:

  • 是的,做到了。非常感谢!
猜你喜欢
  • 2011-01-14
  • 2012-08-15
  • 2011-04-24
  • 2014-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-08
相关资源
最近更新 更多