9

我是 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)

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

4

4 回答 4

15

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

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

应该匹配你模型的“别名”;单数和大写的字母

$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 => file'添加到第一行Form->create()

仅使用数据库的文件

数组到字符串的转换”问题是由于您试图直接将“doc_file”的数据用于数据库。因为这是一个文件上传字段,“doc_file”将包含一个数据数组(“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;
于 2013-04-29T11:15:45.197 回答
3

以防万一有人再次搜索它。这是我的代码(在 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 {...}
    }




}
于 2014-11-17T16:40:09.200 回答
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);  
  }

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

于 2013-04-29T06:41:37.493 回答
1

我从这里找到了在 CakePHP 中上传文件和图像的完整指南 -处理 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(); ?>
于 2016-05-05T07:33:56.223 回答