Save uploaded file with any filename characters

You are viewing revision #2 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#3) »

First of all this is a very common problem, for more details see this post http://www.yiiframework.com/forum/index.php/topic/52052-upload-file-with-any-charset/

I tried to solve this but there is no easy way (or it is not possible).

So the only way that I found is knowing the original character encoding

Suppose the encoding is the Greek, so in this case:

In your model that is related with this file (suppose the table of this model has the id and name_file columns, etc)

public $file;
 public function rules() {
        return array(
		    ...
            array('file', 'file', 'types' => 'doc,pdf,docx,txt,xlsx,doc,xls,png,jpg,gif,rtf'),
			...
        );
 }

	 public beforeSave() {
	      if (parent::beforeSave()) {
				$model->file = CUploadedFile::getInstance($model, 'file');   
				if ($model->file) {
					$name_file = $model->file->name;
					$model->name_file = $name_file;
					$name_file = iconv('UTF-8', 'greek//TRANSLIT//IGNORE', $model->name_file);
					$model->file->saveAs('images/' . $name_file );
					return true;
				}
		   return true;
		   }
		   return false;
	 }

    public function getFile($id) {
		   $encodedFile = iconv('UTF-8', 'greek//TRANSLIT//IGNORE', $this->name_file);
		   $path = 'images/' . $encodedFile; 
		   if (file_exists($path))
			  Yii::app()->getRequest()->sendFile($model->name_file, file_get_contents($path));
		   else
			  throw new CHttpException(404,'The requested file does not exists.'); //or whatever you want because this function is a model method
	}
 
    public function beforeDelete() {
        $path = 'images/' . $this->name_file;
        $path = iconv('UTF-8', 'greek//TRANSLIT//IGNORE', $path);
        @unlink($path);
        return parent::beforeDelete();
    }

In your controller

public function actionCreate()
    {
        $model=new YourModel();
        if(isset($_POST['YourModel']))
        {
            $model->attributes=$_POST['YourModel'];
            $model->save();
        }
        $this->render('create', array('model'=>$model));
    }

The left code is similar to this wiki http://www.yiiframework.com/wiki/2/how-to-upload-a-file-using-a-model

Notes:

If you want to save filenames in another encoding you have to change the greek to the corresponding encoding.

If you want to save filenames in variety encoding (for each file) you have to save the specific encoding into the record (in seperate column) and call the iconv on the fly with the appropriate parameter.