CakePhP 3 - 如何同时上传两个图像文件?

时间:2017-03-19 07:13:04

标签: php cakephp cakephp-3.0

我尝试一次上传两张图片,我的特定图片文件会保存在特定的文件夹中,但由于某种原因,正确的图片无法显示。只有第一张图片会在两次上传中再现并显示出来。有没有办法来解决这个问题?

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

         if (!empty($this->request->data['mainimg'])) {
        $file = $this->request->data['mainimg'];
        $destinationPath = WWW_ROOT . 'project_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->error(__('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 = '/project_img/' . $uniqueFileName; 

        }
    }   

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

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

            $this->Flash->error(__('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 = '/imgone_img/' . $uniqueFileName; 

        }
    }

        $teamproject = $this->Teamproject->patchEntity($teamproject, $this->request->data);
        $teamproject->mainimg = $filePath;
        $teamproject->imgone = $filePath;


        if ($this->Teamproject->save($teamproject)) {
            $this->Flash->success(__('The teamproject has been saved.'));
            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('The teamproject could not be saved. Please, try again.'));
        }


    $users = $this->Teamproject->Users->find('list', ['limit' => 200]);
    $this->set(compact('teamproject', 'users'));
    $this->set('_serialize', ['teamproject']);
}

我认为这是问题发生的地方

    $teamproject = $this->Teamproject->patchEntity($teamproject, $this->request->data);
    $teamproject->mainimg = $filePath;
    $teamproject->imgone = $filePath;

1 个答案:

答案 0 :(得分:2)

您需要在保存图像的同时运行循环,并在图像名称的末尾连接循环索引。事情是你的time()和mt_rand()返回相同的值。 PHP无法正常工作。您需要附加循环索引,这可能会解决您的问题。