我跟着这个guide在CakePHP 3上做了上传。使用该指南,我选择了一个文件,当我点击上传时,它将该文件移动到项目内的指定文件夹,将该文件夹设置为路径,并在数据库中创建一个newEntity。
我现在尝试使用相同的上传来覆盖现有实体(即编辑而不是添加)。
我复制了控制器中的上传功能,并查看和修改它们以用作编辑。但是,在尝试它时,编辑失败,我甚至没有收到错误消息;页面只是刷新,好像什么都没发生一样。
相关表格是Files,它具有以下属性:
这是我在控制器中的功能:
public function edit($id = null)
{
$uploadData = $this->Files->get($id, [
'contain' => []
]);
if ($this->request->is('post')) {
$data = $this->request->data;
if(!empty($data['link']['name'])){
$fileName = $data['link']['name'];
$uploadPath = 'uploads/template/';
$uploadFile = $uploadPath.$fileName;
if(move_uploaded_file($data['link']['tmp_name'],$uploadFile)){
$uploadData = $this->Files->patchEntity($uploadData, $data);
$uploadData->name = $fileName;
$uploadData->link = $uploadPath;
if ($this->Files->save($uploadData)) {
$this->Flash->success(__('File has been uploaded and updated successfully.'));
}else{
$this->Flash->error(__('Unable to upload file, please try again.'));
}
}else{
$this->Flash->error(__('Unable to upload file, please try again.'));
}
}else{
$this->Flash->error(__('Please choose a file to upload.'));
}
}
$files = $this->Files->find('all', ['order' => ['Files.created' => 'DESC']]);
$filesRowNum = $files->count();
$blanks = $this->Files->find('all', ['order' => ['Files.created' => 'DESC']])->first();
$this->set(compact('blanks', 'uploadData', 'files', 'filesRowNum'));
}
这是我的表格:
<?php echo $this->Form->create($uploadData, ['type' => 'file']); ?>
<?php echo $this->Form->input('link', ['type' => 'file', 'class' => 'form-control', 'label' => 'Template Link' ]); ?><br>
<?php echo $this->Form->button(__('Upload File'), ['type'=>'submit', 'class' => 'btn btn-primary', 'style' => 'width:25%;']); ?>
<?php echo $this->Form->end(); ?>
在控制器中,我还尝试将($this->request->is('post')) {
替换为($this->request->is('patch', 'post', 'put')) {
,类似于Cake烘焙编辑页面。
如果说我要上传一个名为Book 2.xlsx
的空白Excel电子表格并想要覆盖Files表格中的第4个数据条目,我会转到URL localhost/project/files/edit/4
,选择文件并提交。
这样做时,不会出现错误消息,Cake错误或flash错误,而在CakePHP请求中,我在POST中有以下数组:
link (array)
name: Book2.xlsx
type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
tmp_name: C:\xampp\tmp\php3B10.tmp
error: 0
size: 7823
答案 0 :(得分:1)
改变这个:
if ($this->request->is('post')) {
对此:
if ($this->request->is('post') || $this->request->is('put')) {
编辑:正如ndm所指出的那样,数组也有效:
$this->request->is(['post', 'put', 'patch'])