简体   繁体   中英

yii how to change uploaded file name

I want to upload a image and change the original name then save it.

Model:

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

Controller:

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

If i save it without any other actions it will work. But how could i change the name of image ? I try something like below:

$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

Is the image attribute must be an instance of CUploadedFile? Anyone help pls

do something like this

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

Thanks for your answer. I figured it out. CUploadedFile.name is read only , so i can't change it. The Model need a new public attribute :

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

Then in the controller:

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

It's works fine.(it's not real code) see here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM