【问题标题】:CakePHP3 - How to limit the upload size of an image to 3mb?CakePHP3 - 如何将图像的上传大小限制为 3mb?
【发布时间】:2017-04-28 05:43:52
【问题描述】:

我正在尝试限制用户可以添加到数据库的图像的上传大小,当用户尝试上传的图像超过3mb?

这是我的控制器代码。

public function add()
{
    $blog = $this->Blogs->newEntity();
    if ($this->request->is('post')) {

         if (!empty($this->request->data['mainimg'])) {
            $file = $this->request->data['mainimg'];
            $destinationPath = WWW_ROOT . 'blogs_img' . DS;
            $filename = $this->request->data['mainimg']['name'];
            $extension = pathinfo($filename, PATHINFO_EXTENSION);
            $arr_ext = array('jpg', 'jpeg','png', 'JPG');

           if (!in_array($extension, $arr_ext)) {

                $this->Flash->adminerror(__('Incorrect Image Format.. Please Try Again'));

            }else{

            $uniqueFileName = time().'_'.mt_rand(10000000, 99999999).'_'.mt_rand(10000000, 99999999).'.'.$extension;
            move_uploaded_file($file['tmp_name'], $destinationPath . '/' . $uniqueFileName);
            $filePath = '/blogs_img/' . $uniqueFileName; 

            }
        }

        $blog = $this->Blogs->patchEntity($blog, $this->request->data);
        $blog->mainimg = $filePath;

        if ($this->Blogs->save($blog)) {
            $this->Flash->adminsuccess(__('The blog has been saved.'));

            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->adminerror(__('The blog could not be saved. Please, try again.'));
        }
    }
    $users = $this->Blogs->Users->find('list', ['limit' => 200]);
    $cattypes = $this->Blogs->Cattypes->find('list', ['limit' => 200]);
    $this->set(compact('blog', 'users', 'cattypes'));
    $this->set('_serialize', ['blog']);
}

【问题讨论】:

  • 尝试了投票的选项,它不起作用
  • 您需要将文件大小调整为 3mb,例如:- $_FILES['uploaded_file']['size'] >= 3000
  • 我做了它一直给我同样的错误。我会尝试另一种方法。
  • $filesize = $this->request->data['mainimg']['size']; if($filesize>3000){echo "max file size is 3 mb";exit();}

标签: php cakephp cakephp-3.0


【解决方案1】:

请参阅Validation::fileSize() 和简单的use it when validating

还有更多与文件相关的验证规则,例如包括 mime 类型。

【讨论】:

    猜你喜欢
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    相关资源
    最近更新 更多