我想在配置文件的用户名中插入图像基本上如果用户输入james作为用户名,它将在james
内创建一个目录webroot/img/users/james/
,并且在运行时上传的图像将是
webroot/img/users/james/uploaded1.jpg
。
<?php
public function add()
{
$user = $this->Users->newEntity();
if($this->request->is('post')) {
$user= $this->Users->patchEntity($user,$this->request->getData());
if($this->Users->save($user)) {
$dir = new Folder();
$path = $dir->create(WWW_ROOT.'img'.DS.'users'.DS.$user->username);
$image_name = $this->request->data['profile_pic']['name'];
$image_tmp = $this->request->data['profile_pic']['tmp_name'];
$destination = WWW_ROOT.'img'.DS.'users'.DS.$user->username.DS.$image_name;
move_uploaded_file($image_tmp,$destination);
$this->request->data['profile_pic'] = $image_name;
$this->request->data['destination'] = $destination;
$this->Flash->success(__('User successfuly added.'));
return $this->redirect(['action' => 'login']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
?>
如果我只使用以下代码
$destination = WWW_ROOT.'img'.DS.'users'.DS.$user->username.DS.$image_name;
我收到以下调试消息:
Notice (8): Array to string conversion [CORE\src\Database\Statement\MysqlStatement.php, line 39]
Notice (8): Array to string conversion [CORE\src\Database\Log\QueryLogger.php, line 92]
如果我使用路径变量
$destination = WWW_ROOT.'img'.DS.'users'.DS.$path.DS.$image_name;
我收到以下调试消息:
Notice (8): Array to string conversion [CORE\src\Database\Statement\MysqlStatement.php, line 39]
Notice (8): Array to string conversion [CORE\src\Database\Log\QueryLogger.php, line 92]
Warning (2): move_uploaded_file(D:\xampp\htdocs\sample\webroot\img\users\1\me.jpg) [<a href='https://secure.php.net/function.move-uploaded-file'>function.move-uploaded-file</a>]: failed to open stream: No such file or directory [APP/Controller\UsersController.php, line 638]
Warning (2): move_uploaded_file() [<a href='https://secure.php.net/function.move-uploaded-file'>function.move-uploaded-file</a>]: Unable to move 'D:\xampp\tmp\php68AA.tmp' to 'D:\xampp\htdocs\sample\webroot\img\users\1\me.jpg' [APP/Controller\UsersController.php, line 638]
答案 0 :(得分:0)
请检查目录权限。您需要确保Apache用户(例如:www-data)具有在img目录中创建目录所需的权限。
sudo chown -vR :www-data /<webroot>/img/
以上命令将img目录的组所有权更改为www-data
sudo chmod -vR g+w /<webroot>/img/
此命令将权限更改为0775(rwxrwxr-x)。基本上为组用户添加写入权限(例如www-data)。
使用以下命令验证所有更改
ls -ld /<webroot>/img/
用适当的路径替换 webroot 。
创建cakephp文件夹并保存新文件
$unused = new Folder(APP.'img/'.$user->username, true);
$file_path = APP.'img/'.$user->username.'/'.$image_name;
if (move_uploaded_file($file, $file_path)) {
//Save the record with $file_path
//Redirect with success message
} else {
//Redirect with error message
}