我正在尝试使用cakephp 2创建多个文件上传。请提供帮助。我是Cakephp的新手 如您所见,我的控制器和视图编码对于单个图像来说都是醒目的。
public function admin_add() {
if ($this->request->is('post')) {
$this->Portfolio->create();
$error_message = $this->Portfolio->checkFileSize($this->request->data);
if( $error_message === true ) {
$this->request->data['Portfolio'] = $this->Common->processMedia($this->request->data['Portfolio']);
//echo '<pre>'; print_r($this->request->data); echo '</pre>';
// exit();
if ($this->Portfolio->save($this->request->data)) {
$this->Session->setFlash(__('The portfolio has been saved'), 'flash_success');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The portfolio could not be saved. Please, try again.'), 'flash_error');
}
} else {
$this->Session->setFlash(__($error_message), 'flash_error');
}
}
$talents = $this->Portfolio->Talent->find('list');
$skills = $this->Portfolio->Skill->find('list', array(
'order' => array('Skill.name ASC')
));
$this->set(compact('talents', 'skills'));
}
查看-
<input type="file" name="data[Portfolio][media_url_file][]" class=" validate[] m-wrap large" id="PortfolioMediaUrlFile" multiple>
我的数据库结构 数据库:-enter image description here
genrated Array-。 使用foreach无法启用将此数组保存到数据库中。
Array
(
[Portfolio] => Array
(
[talent_id] => 435
[title] => asas
[status] => Approved
[type_of_media] => picture
[file] => Array
(
[0] => Array
(
[name] => wi-logo.png
[type] => image/png
[tmp_name] => /tmp/phpn8ne7a
[error] => 0
[size] => 17457
)
[1] => Array
(
[name] => unnamed.png
[type] => image/png
[tmp_name] => /tmp/phpPcqpQw
[error] => 0
[size] => 14362
)
)
[media_url] => Array
(
[0] => Array
(
[name] => wi-logo.png
[type] => image/png
[tmp_name] => /tmp/phpn8ne7a
[error] => 0
[size] => 17457
)
[1] => Array
(
[name] => unnamed.png
[type] => image/png
[tmp_name] => /tmp/phpPcqpQw
[error] => 0
[size] => 14362
)
)
)
)
答案 0 :(得分:0)
如果该文件适用于单个上传,则可以将其扩展为多个。 为什么不创建多个输入字段?每个文件都有自己的输入。 给每个输入一个唯一的名称,然后在控制器中可以循环引用该输入
$this->request->data['Portfolio1']
$this->request->data['Portfolio2']
$this->request->data['Portfolio3']
...
答案 1 :(得分:0)
我想我现在已经明白了这个问题。 您想要保存请求的数据,但是您的数据包含数组,该数组不起作用。 因此,您必须创建一个与您的db结构匹配的数据数组。 在这里,我不明白为什么您有包含相同数据的“文件”和“ mediaurl”。 但是这里是我的解决方案:
$this->Portfolio->create();
for($i = 0;$i < $this->request->data['Portfolio'][file];i++){
$dataArray = [];
//fill in your data which will be the same for each uploaded file
$dataArray['talen_id'] = $this->request->data['Portfolio']['talen_id'];
$dataArray['title'] = $this->request->data['Portfolio']['title'];
$dataArray['status'] = $this->request->data['Portfolio']['status'];
$dataArray['picture'] = $this->request->data['Portfolio']['picture'];
//fill in your data which is different for each uploaded file
$dataArray['media_url'] = $this->request->data['Portfolio']['media_url'][$i]['name'];
$dataArray['file'] = $this->request->data['Portfolio']['file'][$i]['name'];
//now you can save the data
$this->Portfolio->save($dataArray);
}