我想在我的cakephp 3.0应用中上传图片。但我收到错误消息:
Notice (8): Undefined index: Images [APP/Controller/ImagesController.php, line 55]
在cakePHP 3.0中是否已经有一些上传文件(一次多个文件)的例子?因为我只能找到cakePHP 2.x的例子!
我想我需要在ImagesTable.php中添加自定义验证方法?但我无法让它发挥作用。
ImagesTable
public function initialize(array $config) {
$validator
->requirePresence('image_path', 'create')
->notEmpty('image_path')
->add('processImageUpload', 'custom', [
'rule' => 'processImageUpload'
])
}
public function processImageUpload($check = array()) {
if(!is_uploaded_file($check['image_path']['tmp_name'])){
return FALSE;
}
if (!move_uploaded_file($check['image_path']['tmp_name'], WWW_ROOT . 'img' . DS . 'images' . DS . $check['image_path']['name'])){
return FALSE;
}
$this->data[$this->alias]['image_path'] = 'images' . DS . $check['image_path']['name'];
return TRUE;
}
ImagesController
public function add()
{
$image = $this->Images->newEntity();
if ($this->request->is('post')) {
$image = $this->Images->patchEntity($image, $this->request->data);
$data = $this->request->data['Images'];
//var_dump($this->request->data);
if(!$data['image_path']['name']){
unset($data['image_path']);
}
// var_dump($this->request->data);
if ($this->Images->save($image)) {
$this->Flash->success('The image has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The image could not be saved. Please, try again.');
}
}
$images = $this->Images->Images->find('list', ['limit' => 200]);
$projects = $this->Images->Projects->find('list', ['limit' => 200]);
$this->set(compact('image', 'images', 'projects'));
$this->set('_serialize', ['image']);
}
图片add.ctp
<?php
echo $this->Form->input('image_path', [
'label' => 'Image',
'type' => 'file'
]
);
?>
图片实体
protected $_accessible = [
'image_path' => true,
];
答案 0 :(得分:10)
在您的视图文件中,像我这样添加 Users / dashboard.ctp
<div class="ChImg">
<?php
echo $this->Form->create($particularRecord, ['enctype' => 'multipart/form-data']);
echo $this->Form->input('upload', ['type' => 'file']);
echo $this->Form->button('Update Details', ['class' => 'btn btn-lg btn-success1 btn-block padding-t-b-15']);
echo $this->Form->end();
?>
</div>
在您的控制器中添加如下内容,在我的情况下 UsersController
if (!empty($this->request->data)) {
if (!empty($this->request->data['upload']['name'])) {
$file = $this->request->data['upload']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
$setNewFileName = time() . "_" . rand(000000, 999999);
//only process if the extension is valid
if (in_array($ext, $arr_ext)) {
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
move_uploaded_file($file['tmp_name'], WWW_ROOT . '/upload/avatar/' . $setNewFileName . '.' . $ext);
//prepare the filename for database entry
$imageFileName = $setNewFileName . '.' . $ext;
}
}
$getFormvalue = $this->Users->patchEntity($particularRecord, $this->request->data);
if (!empty($this->request->data['upload']['name'])) {
$getFormvalue->avatar = $imageFileName;
}
if ($this->Users->save($getFormvalue)) {
$this->Flash->success('Your profile has been sucessfully updated.');
return $this->redirect(['controller' => 'Users', 'action' => 'dashboard']);
} else {
$this->Flash->error('Records not be saved. Please, try again.');
}
}
在使用此功能之前,请在名为上传/头像的 webroot 中创建一个文件夹。
注意:
中使用了输入(&#39; Name Here&#39;)$this->request->data['upload']['name']
如果要查看数组结果,可以打印它。
它的作品就像 CakePHP 3.x
中的魅力答案 1 :(得分:2)
也许以下内容会有所帮助。这种行为可以帮助您轻松上传文件!
http://cakemanager.org/docs/utils/1.0/behaviors/uploadable/
如果你挣扎,请告诉我。
格尔茨
答案 2 :(得分:1)
现在每个人都在这里为他的插件做广告,让我也这样做。我已经检查了在另一个问题中链接的可上传行为,这很简单,看起来已经完成了一半。
如果您想要在企业级别上进行扩展的完整解决方案,请检查https://msdn.microsoft.com/en-us/library/aa365600%28v=vs.85%29.aspx。它有一些我在任何其他实现中都没有看到的功能,比如确保在真正许多文件的情况下确保不会遇到文件系统限制。它与FileStorage一起处理图像。您可以单独使用它们,也可以组合使用,它遵循Imagine。
它完全基于事件,您可以通过实现自己的事件侦听器来更改所有内容。这将需要一些中级水平的CakePHP经验。
有一个SoC可以看出实现它有多容易。以下代码取自它,这是一个完整的例子,请参阅快速入门指南,它更详细。
auto pipe = CreateFile(LOCAL_PIPE_NAME,
GENERIC_READ | GENERIC_WRITE, // read access
0, // no sharing
NULL, // default security attributes
OPEN_EXISTING, // opens existing pipe
0, // default attributes
NULL); // no template file
if (pipe == INVALID_HANDLE_VALUE)
throw(std::runtime_error("Failed to open local pipe: " + std::to_string(GetLastError())));
答案 3 :(得分:0)
/*Path to Images folder*/
$dir = WWW_ROOT . 'img' .DS. 'thumbnail';
/*Explode the name and ext*/
$f = explode('.',$data['image']['name']);
$ext = '.'.end($f);
/*Generate a Name in my case i use ID & slug*/
$filename = strtolower($id."-".$slug);
/*Associate the name to the extension */
$image = $filename.$ext;
/*Initialize you object and update you table in my case videos*/
$Videos->image = $image;
if ($this->Videos->save($Videos)) {
/*Save image in the thumbnail folders and replace if exist */
move_uploaded_file($data['image']['tmp_name'],$dir.DS.$filename.'_o'.$ext);
unlink($dir.DS.$filename.'_o'.$ext);
}
答案 4 :(得分:0)
我们正在使用https://github.com/josegonzalez/cakephp-upload在我们的制作应用中取得巨大成功,并且已经这么做了很长时间。
非常支持使用“Flysystem”(https://flysystem.thephpleague.com/) - 这是来自特定文件系统的抽象 - 所以从普通的本地文件系统转移到S3是一个明智的选择,或Dropbox或无论你想要什么地方: - )
你可以在这里找到相关的(高质量)文件上传插件:https://github.com/FriendsOfCake/awesome-cakephp#files - 我也成功地使用了“Proffer”,它绝不是“差不多完成”或类似的东西 - 两者都是有我所有的建议,并准备好在我的眼中生产!