在cakephp 2.3中上传文件

时间:2013-04-28 11:05:05

标签: cakephp file-upload cakephp-2.3

我是cakephp的新手,我正在尝试使用cakephp创建一个简单的文件上传2.3这里是我的控制器

public function add() {
    if ($this->request->is('post')) {
        $this->Post->create();
           $filename = WWW_ROOT. DS . 'documents'.DS.$this->data['posts']['doc_file']['name']; 
           move_uploaded_file($this->data['posts']['doc_file']['tmp_name'],$filename);  


        if ($this->Post->save($this->request->data)) {
            $this->Session->setFlash('Your post has been saved.');
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash('Unable to add your post.');
        }
     }
 }

和我的add.ctp

echo $this->Form->create('Post');
echo $this->Form->input('firstname');
echo $this->Form->input('lastname');
echo $this->Form->input('keywords');
echo $this->Form->create('Post', array( 'type' => 'file'));
echo $this->Form->input('doc_file',array( 'type' => 'file'));
echo $this->Form->end('Submit')

它保存了数据库中的名字,姓氏,关键字和文件名,但是我要保存在app / webroot / documents中的文件没有保存,有人可以帮忙吗?感谢

  

更新

     

thaJeztah我按照你说的做了但是如果我没错的话,它会给出一些错误

public function add() {
     if ($this->request->is('post')) {
         $this->Post->create();
            $filename = WWW_ROOT. DS . 'documents'.DS.$this->request->data['Post']['doc_file']['name']; 
           move_uploaded_file($this->data['posts']['doc_file']['tmp_name'],$filename);



         if ($this->Post->save($this->request->data)) {
             $this->Session->setFlash('Your post has been saved.');
             $this->redirect(array('action' => 'index'));
         } else {
            $this->Session->setFlash('Unable to add your post.');
         }
     }

 }
  

和我的add.ctp

 echo $this->Form->create('Post', array( 'type' => 'file'));
 echo $this->Form->input('firstname'); echo $this->Form->input('lastname');
 echo $this->Form->input('keywords');
 echo $this->Form->input('doc_file',array( 'type' => 'file'));
 echo $this->Form->end('Submit') 
  

,错误是

     

注意(8):数组到字符串的转换   [CORE \ Cake \ Model \ Datasource \ DboSource.php,第1005行]

     

数据库错误错误:SQLSTATE [42S22]:找不到列:1054未知   “字段列表”中的“数组”列

     

SQL查询:INSERT INTO first.posts(firstname,lastname,keywords,   doc_file)VALUES('dfg','cbhcfb','dfdbd',Array)

     

和Victor我也做了你的版本,它也不起作用。

4 个答案:

答案 0 :(得分:14)

您似乎使用了错误的“密钥”来访问发布的数据;

$this->data['posts'][....

应匹配您Model的'别名'; 单数 captial 第一个字母

$this->data['Post'][....

此外,$this->data$this->request->data的向后兼容性包装器,所以最好使用它;

$this->request->data['Post'][...

要检查发布数据的内容并了解其结构,您可以使用此进行调试;

debug($this->request);

确保启用调试,方法是将debug设置为12内的app/Config/core.php

更新;复制表格标签!

我刚刚注意到你还在代码中创建了多个(嵌套)表单;

echo $this->Form->input('keywords');

// This creates ANOTHER form INSIDE the previous one!
echo $this->Form->create('Post', array( 'type' => 'file'));

echo $this->Form->input('doc_file',array( 'type' => 'file'));

嵌套表单将从不工作,删除该行并添加'type =>将文件'发送到第一个Form->create()

仅使用文件名称作为数据库

“数组到字符串转换”问题是由于您尝试直接将“doc_file”数据用于数据库这一事实。因为这是一个文件上传字段,'doc_file'将包含 Array 数据('name','tmp_name'等)。

对于数据库,您只需要该数组的“名称”,因此您需要在将数据保存到数据库之前修改数据。

示例这种方式;

// Initialize filename-variable
$filename = null;

if (
    !empty($this->request->data['Post']['doc_file']['tmp_name'])
    && is_uploaded_file($this->request->data['Post']['doc_file']['tmp_name'])
) {
    // Strip path information
    $filename = basename($this->request->data['Post']['doc_file']['name']); 
    move_uploaded_file(
        $this->data['Post']['doc_file']['tmp_name'],
        WWW_ROOT . DS . 'documents' . DS . $filename
    );
}

// Set the file-name only to save in the database
$this->data['Post']['doc_file'] = $filename;

答案 1 :(得分:2)

..确保文件目录已存在并检查您是否有权写入该文件目录?如果它不存在则创建它或在您的代码中检查它是否存在并创建它,如果它不存在: 将检查目录是否存在的代码示例并创建它然后上传文件 -

$dir = WWW_ROOT. DS . 'documents';
 if(file_exists($dir) && is_dir($dir))
 {
    move_uploaded_file($this->data['posts']['doc_file']['tmp_name'],$filename);  
 }
 elseif(mkdir($dir,0777))
 {
  move_uploaded_file($this->data['posts']['doc_file']['tmp_name'],$filename);  
  }

还确保您没有上传空白/空文件 - 它可能会失败。

答案 2 :(得分:2)

只是因为有人再次搜索它。这是我的代码(在Cakephp 2.5.5上测试和使用)。它基于http://www.templemantwells.com.au/article/website-development/cakephp-image-uploading-with-database& http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::file

查看文件(* .ctp)

    <?php 
    echo $this->Form->create('Image', array('type' => 'file'));
?>


    <fieldset>
        <legend><?php echo __('Add Image'); ?></legend>
    <?php


        echo $this->Form->input('Image.submittedfile', array(
            'between' => '<br />',
            'type' => 'file',
            'label' => false
        ));
        // echo $this->Form->file('Image.submittedfile');

    ?>
    </fieldset>
<?php echo $this->Form->end(__('Send My Image')); ?>

控制器功能(* .php)

    public function uploadPromotion() {

    // Custom
    $folderToSaveFiles = WWW_ROOT . 'img/YOUR_IMAGE_FOLDER/' ;




    if (!$this->request->is('post')) return;        // Not a POST data!


    if(!empty($this->request->data))
    {
        //Check if image has been uploaded
        if(!empty($this->request->data['Image']['submittedfile']))
        {
                $file = $this->request->data['Image']['submittedfile']; //put the data into a var for easy use

                debug( $file );

                $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
                $arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions

                //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
                    $newFilename = $file['name']; // edit/add here as you like your new filename to be.
                    $result = move_uploaded_file( $file['tmp_name'], $folderToSaveFiles . $newFilename );

                    debug( $result );

                    //prepare the filename for database entry (optional)
                    //$this->data['Image']['image'] = $file['name'];
                }
        }

        //now do the save (optional)
        //if($this->Image->save($this->data)) {...} else {...}
    }




}

答案 3 :(得分:1)

我已经找到了从CakePHP上传文件和图片的完整指南 - Handling File Uploads in CakePHP

示例代码如下所示。

<强>控制器:

$fileName = $this->request->data['file']['name'];
$uploadPath = 'uploads/files/';
$uploadFile = $uploadPath.$fileName;
if(move_uploaded_file($this->request->data['file']['tmp_name'],$uploadFile)){
    //DB query goes here
}

查看:

<?php echo $this->Form->create($uploadData, ['type' => 'file']); ?>
    <?php echo $this->Form->input('file', ['type' => 'file', 'class' => 'form-control']); ?>
    <?php echo $this->Form->button(__('Upload File'), ['type'=>'submit', 'class' => 'form-controlbtn btn-default']); ?>
<?php echo $this->Form->end(); ?>