【问题标题】:CakePHP: Saving a File Field with Expanded Data Array to DBCakePHP:将具有扩展数据数组的文件字段保存到数据库
【发布时间】:2014-04-05 14:05:49
【问题描述】:

上传文件时,您通常会为该字段创建一个数组。比如模型是Document,字段是submittedfile:

$this->request->data['Document']['submittedfile'] = array(
'name' => 'conference_schedule.pdf',
'type' => 'application/pdf',
'tmp_name' => 'C:/WINDOWS/TEMP/php1EE.tmp',
'error' => 0,
'size' => 41737,
);

无法将数组保存到数据库,因为该字段无法将 'submittedfile' 数组保存到数据库 'submittedfile' 列。但是,我只需要数据库的 submittedfile 字段中上述数组的 name 部分。尝试了很多方法这里有两种:

1在控制器方法中调用保存方法之前,将提交的文件从数组转换为字符串在控制器方法中。 (问题无法使用 cakePHP 验证 fileSize 和 uploadError,因为它们需要 ['tmp_name'] 才能工作。)

public function addDocument(){
$this->request->data['Document']['submittedfile'] = $this->request->data['Document']['submittedfile']['name'];
$this->Document->save($this->request->data);}

2在Controller方法中调用save方法之前,在beforeSave回调方法中将提交的文件从数组转为字符串。 (问题是我得到错误 Illegal string offset 'name')

public function beforeSave($options = array()){
$this->data['Document']['submittedfile'] = $this->data['Document']['submittedfile']['name'];}

关于将上传的文件类型数组保存到数据库的任何答案?

【问题讨论】:

    标签: arrays file cakephp upload


    【解决方案1】:

    如果要保存数组,可以store it as JSON 或serialized array。

    各有优势有讨论here

    关于你的两个解决方案,也许第二个更好。

    在beforeSave 内,请debug($this->data); 了解您正在获得什么,以及如何访问'name'

    您如何处理文件上传?这应该分开处理:上传具有随机名称的文件并将该名称存储在数据库中。

    【讨论】:

    • 我按照你的建议使用调试,发现它给出了以下内容。
    • 我按照您的建议使用调试,但它给了我数组结构。它表明使用$this->data['Document']['submittedfile']['name'] 应该返回正确的值。问题似乎在于分配给$this->data['Document']['submittedfile'],因为如果我回显$this->data['Document']['submittedfile']['name'],则显示的值没有非法偏移错误。ted 发现它给出了以下内容。
    • 对不起,第一个评论点击输入错误。
    【解决方案2】:

    我不确定你将如何处理数据库中的名称,我猜你也需要上传文件。

    使用这个:Uploader

    【讨论】:

      【解决方案3】:

      问题:控制器中的多个保存方法使用了不同的 $this->data 数组。试图简化发布的代码并从代码中解决问题。未显示的原始代码包含在adddocument() 控制器中调用的两个save() 方法,其中一个没有将$this->data['Document']['submittedfile']['name'] 传递给它。这导致了非法字符串偏移错误:

      提示 1(推荐):

      使用 isset() 检查变量是否存在,然后再尝试在 beforeSave() 方法中对其进行操作:

      public function beforeSave($options=array())
      {
        if(isset($this->data['Document']['submittedfile']['name']))
        {$this->data['Document']['submittedfile'] = $this->data['Document']['submittedfile']['name'];
        }
         return true;
      }
      

      提示 2:

      禁用回调(即 beforeSave、afterValidate 等)被控制器中的其他保存方法调用。如果这些保存不需要在保存之前处理其数据:

      $this->Document->saveField('submittedfile', $yourvalue, array('callbacks'=>false))
      

      感谢所有花时间帮助我的人@cornelb 和@skywalker。

      【讨论】:

        猜你喜欢
        • 2014-02-09
        • 1970-01-01
        • 2012-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-25
        • 1970-01-01
        相关资源
        最近更新 更多