2012-04-19 106 views
0

所以我遇到了麻煩,我的數據保存在CakePHP中。如果我上傳圖片(意思是['PictureForm'] ['file'] ['name']存在),一切正常,數據被保存。但是,如果['PictureForm'] ['file'] ['name']爲空,並且['PictureForm'] ['url']存在,則圖像被正確保存在磁盤上,但是$ this-> PictureForm - >保存($ this-> data)失敗。CakePHP:保存數據時出錯

任何人看到任何公然錯誤的代碼?

if (isset($this->data['PictureForm'])) { 
          ///////////////////////////////////////////////////////DEV 
          if(!$this->data['PictureForm']['file']['name']) { 
            if (!$this->data['PictureForm']['url']) { 
              $this->Session->setFlash('Error: no image URL or file given!'); 
              $this->redirect(array('action' => '/')); 
            } else { 
              $fileExtension = getExtension($this->data['PictureForm']['url']); 
              $this->request->data['PictureForm']['filename'] = randFilename() . "." . $fileExtension; 
              file_put_contents('files/picture/' . $this->data['PictureForm']['filename'], file_get_contents($this->data['PictureForm']['url'])); 
            } 
          } else { //file was uploaded 
            $fileExtension = getExtension($this->data['PictureForm']['file']['name']); 
            if (!$fileExtension) { 
              $this->Session->setFlash('Error: no file extension!'); 
              $this->redirect(array('action' => '/')); 
            } 
            $this->request->data['PictureForm']['filename'] = randFilename() . "." . $fileExtension; 
            move_uploaded_file($this->data['PictureForm']['file']['tmp_name'], "files/picture/" . $this->data['PictureForm']['filename']); 
          } 
          $this->request->data = Sanitize::clean($this->request->data, array('encode' => false)); 
          if ($this->PictureForm->save($this->data)) { 
            resizeUpload($this->data['PictureForm']['filename']); 
            $this->Session->setFlash('Picture <a href="/spootur/media/p/' . $this->data['PictureForm']['filename'] . '">saved</a>'); 
            $this->redirect(array('action' => 'p/' . $this->data['PictureForm']['filename'])); 
          } else { 
            $this->Session->setFlash('Error: could not save to db' . $this->data['PictureForm']['filename']); 
            $this->redirect(array('action' => '/')); 
          } 
        } 
+0

代碼中直接粘貼到這個問題,並沒有鏈接到場外。這使得回答更容易,以及稍後前來閱讀的人更容易。 – Treffynnon 2012-04-19 21:53:54

回答

1

如果保存失敗,在其他塊,而不是重定向嘗試查看驗證錯誤:

if ($this->PictureForm->save($this->data)) { 
    // code 
} else{ 
    debug($this->PictureForm->validationErrors); 
} 
+0

好的謝謝。我從來不知道如何使用debug(),所以一定會派上用場。 – 2012-04-20 03:25:29