CakePHP3 - 如何将图像的上传大小限制为3mb?

时间:2017-04-28 05:43:52

标签: php cakephp cakephp-3.0

我试图限制用户可以添加到数据库的图像的上传大小,我该怎么做并在用户图像时显示("警告信息")试图上传超过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']);
}

1 个答案:

答案 0 :(得分:1)

请参阅Validation::fileSize(),只需use it when validating

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