cakephp上传函数 - move_uploaded_file问题

时间:2014-08-21 07:43:23

标签: php cakephp upload

我在cakephp中创建了一个上传功能,它想要做的就是上传一张图片 并将其移动到app / webroot / media目录,然后将图像名称保存到数据库中 它可以使用函数调用。

目前,它可以上传图像并将图像名称保存在数据库中,但它不会将文件移动到 app / webroot / media目录。我试图逐个打破代码并仔细检查我使用的功能,但我似乎无法找到问题。我希望不同的一双眼睛可以启发我。任何帮助/建议非常感谢tnx。

public function upload() {
if (!empty($this->request->data['ModelName']['name'])) {
$file = $this->request->data['ModelName']['name']; 

$path = $file['name'];
$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));

$path2 = $file['tmp_name'];
$ext2 = pathinfo($path2, PATHINFO_BASENAME);

$arr_ext = array('jpg', 'jpeg', 'gif','png'); 

if (in_array($ext, $arr_ext)) {
move_uploaded_file($ext2, APP_DIR . '/webroot/media/' . $file['name']);
$this->request->data['ModelName']['name'] = $file['name'];
}
}

if($this->ModelName->save($this->request->data)) {
echo 'saved';
} else {
echo 'not saved';
}
$this->autoRender = FALSE;
$this->redirect($this->referer());
}

2 个答案:

答案 0 :(得分:0)

使用move_uploaded_file()上传图像时,在第一个参数中,您只需要获取整个tmp文件(即$ path2)。在第二个参数中,您可以通过“WWW_ROOT / media”

直接使用webroot的完整路径

答案 1 :(得分:0)

来自我的控制器的代码。希望这会对你有帮助。

if(!empty($this->data['Post']['filename']['name']))
            {
                $file=$this->data['Post']['filename'];
                $ary_ext=array('jpg','jpeg','gif','png'); //array of allowed extensions
                $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
                if(in_array($ext, $ary_ext))
                {
                    move_uploaded_file($file['tmp_name'], WWW_ROOT . 'media/' . time().$file['name']);
                    $this->request->data['Post']['filename'] = time().$file['name'];
                }
            }