我想为两个变量分配一个文件字段输入,然后我想将这两个变量保存到两个不同的目录中,这是我的代码:
控制器:
if(isset($_POST['Articles']))
{
$model->attributes=$_POST['Articles'];
$model->date = date('Y-m-d H:i:s');
$model->display = 1;
$model->visits = 0;
$model->image = CUploadedFile::getInstance($model, 'image');
$model->thumbnail = CUploadedFile::getInstance($model, 'image');
if($model->save()){
if(!empty($model->image)){
$model->image->saveAs(getcwd()."/images/articles/".$model->image);
if(!empty($model->thumbnail))
if(!$model->thumbnail->saveAs(getcwd()."\images\articles\thumbnails/".$model->thumbnail))
$thumbnail = Yii::app()->image->load(getcwd()."/images/articles/thumbnails/".$model->thumbnail);
$thumbnail->resize(64, 64);
$thumbnail->save();
}
$this->redirect(array('view','id'=>$model->id));
}
保存模型后,缩略图dir仍然为空,我从图像扩展中得到一个错误,没有要加载的文件,所以如何在两个目录中保存这个图像两次?
答案 0 :(得分:4)
你不需要2个2个图像的实例,默认情况下saveAs删除临时文件,所以你可以做这样的事情:
if(isset($_POST['Articles']))
{
$model->attributes=$_POST['Articles'];
$model->date = date('Y-m-d H:i:s');
$model->display = 1;
$model->visits = 0;
$model->image = CUploadedFile::getInstance($model, 'image');
if($model->save()){
if(!empty($model->image)){
$model->image->saveAs(getcwd()."/images/articles/".$model->image,false);//here's a trick
if($model->image->saveAs(getcwd()."\images\articles\thumbnails/".$model->image) {
$thumbnail = Yii::app()->image->load(getcwd()."/images/articles/thumbnails/".$model->image);
$thumbnail->resize(64, 64);
$thumbnail->save();
}
$this->redirect(array('view','id'=>$model->id));
}
你也可以不保存图像,然后重新加载 - 即时完成。 EUploadedImage。