yii 如何更改上传的文件名

yii how to change uploaded file name

我想上传一张图片,把原来的名字改一下再保存。

型号:

public function rules()
    {
        return array(
            array('image', 'file', 'types'=>'jpg, gif, png'),
        );
    }

控制器:

$model->image = CUploadedFile::getInstanceByName('image');

如果我不执行任何其他操作就保存它,它将起作用。 但是我怎么能改变图像的名称呢?我尝试如下操作:

$model->image->name = "xxx";  //CUploadedFile.name readonly

if($model->save())
    $model->images->saveAs(some_path_else.newname);  //the files's new name is different from database


 $model->image = "abc.jpg";  //wont save it

图片属性必须是CUploadedFile的实例吗? 有人帮忙吗

做这样的事情

$uploadedFile = CUploadedFile::getInstance($model, 'image');
if (!empty($uploadedFile)) {
    //new name will go here
    $model->image = strtotime($this->getCurrentDateTime()) . '-' .$uploadedFile;
}
//this will save the image with new name
$uploadedFile->saveAs(Yii::app()->basePath.'/../public/images/user/' . $model->image);

感谢您的回答。 我想到了。 CUploadedFile.name 是只读的,所以我无法更改它。 模型需要一个新的 public 属性:

public $file;    
public function rules()
        {
            return array(
                array('file', 'file', 'types'=>'jpg, gif, png'),
                array('iamge', 'length'=>'255'),
            );
        }

然后在控制器中:

$model->file = CUploadedFile::getInstanceByName('image');
$model->file->saveAs(Yii::app()->basePath.'/../public/images/user/' . $model->image);
$model->image = $model->file->name;

它工作正常。(这不是真正的代码) see here