在CakePHP的2.3文件上传(file upload in cakephp 2.3)

2019-09-01 07:53发布

我在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')

这样可以节省名字,姓氏,关键字和DB文件的名称,但我想在app / webroot的/文件保存为不节能,谁能帮助文件? 谢谢

更新

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):Array对字符串的转换[CORE \蛋糕\模型\数据源\ DboSource.php,线1005]

数据库错误错误:SQLSTATE [42S22]:列未找到:在“字段列表” 1054未知列“阵”

SQL查询:INSERT INTO first.posts(名字,姓氏,关键字doc_file)VALUES( 'DFG', 'cbhcfb', 'dfdbd',阵列)

和维克多我做你的版本太多,它不工作了。

Answer 1:

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

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

应与你示范“别名”; 奇异captial第一个字母

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

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

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

要检查发布数据的内容,并了解它的结构如何,可以使用此调试它;

debug($this->request);

只是一定要启用调试,通过设置debug12的内部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'));

嵌套形式将永远不会工作,删除该行,并添加“类型=>文件”到第一Form->create()

数据库仅使用文件

“Array对字符串的转换”问题是事实,你要直接使用“doc_file”的数据为你的数据库的事业。 因为这是一个文件上传字段,“doc_file”将包含数据的Array(“姓名”,“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;


Answer 2:

..ensure的文件目录已经存在,并检查是否具有写入权限呢? 如果它不存在,如果存在的话创建它或在你的代码检查和创建它,如果它不存在:例如代码,将检查目录是否有与否,并创建它,然后上传文件 -

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

也确保不会上传空/空文件 - 它可能会失败。



Answer 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/佣工/ form.html#表单助手::文件

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




}


Answer 4:

我已经找到了完整的指南,从这里上传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(); ?>


文章来源: file upload in cakephp 2.3