我试图一次上传两个图像,我的特定图像文件保存在特定文件夹中,但由于某种原因,正确的图像没有显示。只有第一张图像会在两次上传和显示中重现。有没有办法来解决这个问题?
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;
最佳答案
您需要在保存图像时运行循环,并将循环索引连接到图像名称的末尾。问题是你的 time() 和 mt_rand() 返回相同的值。 PHP 不是这样工作的。您需要附加循环索引,这可能会解决您的问题。
关于php - CakePhP 3 - 如何同时上传两个图像文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42883931/