【发布时间】:2015-01-25 05:17:46
【问题描述】:
当我添加文件类型检查时,事情就坏了:)
我原本只有这条规则:
array('image, pictures, documents', 'default', 'setOnEmpty' => true, 'value' => ''),
一切都很好,除了上传的文件类型没有安全性。所以我添加了规则(见下文)以仅允许某些文件类型、最大大小和最大数量。
问题:添加文件类型检查后,更新全部中断。表单上未使用的文件字段被设置为 NULL,而不是之前数据库中的旧值。
症状:当我编辑具有图像或文档集(图像、图片或文档)的记录时,它们都会被重置!我有更多字段,例如名称、描述等。我可以只编辑名称,而不触及任何上传的文件字段。噗,都是空的。因此,当模型保存时,它会用任何内容替换现有值。所以我们丢失了为该记录保存的图像或文档!
现在,如果我确实尝试更改其中一个文件。假设我有一张图片,但没有图片或文档...如果我添加一个文档,文档会保存到数据库中,但原始图像会被删除(数据库中的值消失了)。它不应该被触摸。
表单上的其他字段仍然存在,因此它们不会神奇地被重置。名称,描述,它们都还在。只有文件验证规则定义的那些会被重置。
当我创建新记录时,它会正常工作。
似乎只是在更新记录时,所有文件字段在保存到数据库时都会重置。
型号:
public function rules()
{
return array(
array('image','file', 'allowEmpty' => true, 'types'=>'jpg, gif, png, jpeg', 'maxSize'=>1024 * 1024 * 1, 'tooLarge'=>'File has to be smaller than 1MB'),
array('pictures','file', 'allowEmpty' => true, 'types'=>'jpg, gif, png, jpeg', 'maxSize'=>1024 * 1024 * 1, 'tooLarge'=>'File has to be smaller than 1MB', 'maxFiles' => 10, 'tooMany'=>'You have selected too many files!'),
array('documents','file', 'allowEmpty' => true, 'types'=>'doc, docx, pdf, ppt, psd, rtf, txt, xls, xlsx, csv', 'maxSize'=>1024 * 1024 * 10, 'tooLarge'=>'File has to be smaller than 10MB', 'maxFiles' => 10, 'tooMany'=>'You have selected too many files!'),
);
}
控制器:
public function actionUpdate($id)
{
$uid = Yii::app()->user->id;
$model=$this->loadModel($id);
if ( $model->uid !== $uid ) {
$this->redirect(array('index'));
}
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
$origImage = $model->image;
$origPictures = $model->pictures;
$origDocuments = $model->documents;
if(isset($_POST['Titles']))
{
$model->attributes=$_POST['Titles'];
$model->image = $origImage; // we are not ready to reset them yet
$model->pictures = $origPictures; // we are not ready to reset them yet
$model->documents = $origDocuments; // we are not ready to reset them yet
$imageInstance = CUploadedFile::getInstance($model, 'image');
$picturesInstance = CUploadedFile::getInstances($model, 'pictures');
$documentsInstance = CUploadedFile::getInstances($model, 'documents');
if($model->validate())
{
//die(var_dump($model->image)); //POOF - Here is where it's reset
if($model->save())
{
// do more stuff here
}
}
}
}
你可以看到我的“POOF - Here is its reset”评论,这里我有一个 die 命令来显示 $model->image 的值。使用 die() 可以让我点击刷新并使测试上传更容易。
该 die 命令将 $model->image 显示为 NULL...它应该是更新之前数据库中的旧值(当它未在表单中使用时)。
为什么 $model->validate 将 'image' 设置为 null?
“图像”值示例,JSON 编码数组:
[{"image":"18a18923c449cb0b6f2326ea43f2aec6.jpg","thumb":"18a18923c449cb0b6f2326ea43f2aec6_thumb.jpg"}]
注意:文档存储更多信息,例如文件扩展名和随机哈希之前的文件原始名称。
也许 JSON 数组(上图)未能通过验证,这就是它设置为 NULL 的原因?如果是这样,我如何允许在这些字段中保存 JSON 数组?
JSON 允许我跟踪文件名、缩略图、扩展名、名称、描述等内容。所以稍后我可以允许用户添加自定义名称或描述或每个图像(或文档)。所以我确实需要更多信息,而不仅仅是文件名。
如果不是因为需要名称、描述等...我只会存储文件名,并在其中添加“_thumb”作为缩略图。不幸的是,我需要保存更多数据。
非常感谢任何帮助!
【问题讨论】:
标签: mysql json image validation yii