提问者:小点点

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.');
        }
     }
 }

还有我的补充。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')

它将firstname、lastname、关键字和文件名保存在数据库中,但我要保存在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.');
         }
     }

 }

还有我的补充。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查询:插入到first.posts(firstname,lastname,关键字,doc_file)值('dfg','cbhcfb','dfdbd',数组)

维克多,我也做了你的版本,它不太管用。


共3个答案

匿名用户

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

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

应与您模型的“别名”匹配;单数首字母和大写首字母

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

还有,$this-

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

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

debug($this->request);

只需确保在app/Config/core内将debug设置为12即可启用调试。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'));

嵌套表单永远不会工作,请删除该行并添加“类型”=

数组到字符串转换问题是由于您试图直接将doc_file的数据用于数据库而引起的。因为这是一个文件上传字段,doc_file将包含一个数据数组(名称、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;

匿名用户

以防万一有人再次搜索它。这是我的代码(已测试)

查看文件(*.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 {...}
    }




}

匿名用户

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

$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);  
  }

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