当前位置: 首页 > 知识库问答 >
问题:

cakephp 2.3中的文件上载

梅欣然
2023-03-14

我是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个答案

景正文
2023-03-14

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

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

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

景帅
2023-03-14

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

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




}
齐昆
2023-03-14

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

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

 类似资料:
  • 类型DiskFileUpload中的方法ParserRequest(HttpServletRequest,int,long,String)不适用于参数(HttpServletRequest) 当我以服务器的身份运行时...它会在控制台出现错误 这是我在此代码中的代码出错,因为类型DiskFileUpload中的方法parseRequest(HttpServletRequest,int,long,S

  • 我正在使用PHP构建一个web应用程序。我正在创建一个文件上传部分,但我有问题。 上载php: 对于图像来说,它工作得很好。但当我尝试检查上传mp4文件时会发生什么情况。它的回声文件已经存在,对不起,只有JPG,JPEG,PNG

  • 我想解析将文件作为多部分/表单数据接受的请求主体。目前,当我尝试将inputStream打印为字符串时,我得到如下结果: 下面是我的控制器。Java语言 上载txt文件 所以基本上,我是在发送sb。toString()返回响应正文。 我的问题是,如何仅从我收到的上述回复中提取内容数据? 我尝试使用多部分文件,但仍然没有成功

  • 问题内容: 但我不断收到“失败”错误消息框 Index.cshtml 控制者 Files.cshtml Global.asax 问题答案: 更好的方法是使用jquery表单插件。 这是示例: Html.BeginForm 行动方法 进度条 jQuery和表单脚本 更新中… 两次遇到调用操作方法问题的人都归功于Ajax.BeginForm,只需将其转换为Html.BeginForm()。

  • 问题内容: Jenkins构建中的每个文件参数“帮助文本”, 接受来自浏览器的文件提交作为构建参数。上载的文件将放置在工作空间中的指定位置,然后您的构建可以访问和使用该文件。这在许多情况下很有用,例如: 让人们对其构建的工件进行测试。 通过允许用户放置文件来自动执行上载/发布/部署过程。 通过上传数据集执行数据处理。 提交的文件的名称在环境变量中可用,该环境变量的名称与文件位置相同。例如,如果将文

  • 问题内容: 有谁知道一种通过Ajax上载文件并使用支持PlayFramework将文件上载转换为File对象的功能的桌面拖放功能的方法吗? 我尝试了几种不同的方法,但均无法正常工作。 问题答案: 这是我成功的尝试: 编辑路线文件并添加 我们的控制器是,我将使用它来简化它。 编辑您的应用程序控制器类 在app / views / Application文件夹/包中编辑您的Application.ht

  • filename变量用于获取最新文件的名称。我的目标是监视文件夹,每当检索到新文件时,使用boto3自动将其上载到s3 bucket。 会话=BOT3。会话(aws\u access\u key\u id='aws\u access\u key\u id',aws\u secret\u access\u key='aws\u secret\u access\u key',region\u name

  • 我正在尝试将文件上传到s3存储桶中的文件夹中。我正在用PHP做以下工作: 桶名是发送到PHP的字符串,表示使用正斜杠的子文件夹: 然而,当我将一个新图像上传到我的bucket时,它会被上传到bucket root。如何将此文件上载到bucket中的子文件夹? 谢谢