0

我正在尝试处理重复的文件名。如果用户上传了一个名为“file”的文件,那么另一个用户上传了一个名为“file”的文件,我希望能够将 1 添加到新文件中,因此它现在称为“1file”。我能够做到这一点,但我的问题是当有人第三次上传“文件”时,它会覆盖“1file”,我需要增加 1。我正在使用 yii 框架

这是我在控制器中的功能:

function actionIndex(){
  //$dir = Yii::getPathOfAlias('application.images');
  //$dir is a variable that will hold the files uploaded
  $dir = Yii::app()->controller->module->cssFolder;
  //uploaded is a flag to see if we need to display a success/error message
  $uploaded = false;
  $model=new CssUpload();
  if(isset($_POST['CssUpload'])){
      $model->attributes=$_POST['CssUpload'];
      //see if file is correct format and allows us to see and save the file
      $file=CUploadedFile::getInstance($model,'file');
      if($model->validate()){
         $i = 0;
         //trying to add a int to the front/end of a duplicate file
         //able to handle the duplicate one time then gets stuck in an infinete loop
         //(it actually breaks on the first duplictae but it uploads)
        do{
            if(file_exists($dir.'/'.$file)){
                    //increase $i by 1 every time it loops through
                   $i++;
                   //for test purposes only
                   echo $i;
                  //upload the file
                  $uploaded = $file->saveAs($dir.'/'.$i.$file->getName());
                   //stops the infinute loop
                   break;
           }

       }while(file_exists($dir.'/'.$file));
         //upload the original file with no new extensions
         $uploaded = $file->saveAs($dir.'/'.$file->getName());

    }
  }

  $this->render('index', array(
     'model' => $model,
     'uploaded' => $uploaded,
     'dir' => $dir,
  ));

}

4

2 回答 2

1

Well I think you have two options:

  • append something like microtime() to the end of the filename, that way it's virtually impossible for you to have the same file name twice.

  • if you need the files to be kept in order and don't want to use the approach above, then you'd have to store the last inserted number in a database and then retrieve it, increment and store again.

I use the YII framework as well, but can't remember of anything specific to Yii that would help you here.

于 2012-11-14T20:48:20.033 回答
0

您将必须扫描所有可能与该模式匹配的文件。

在这里查看如何使用通配符搜索查找文件:PHP file_exists and wildcard

从那里你 acn 做两件事。

  1. 处理每个文件,读取数字,然后选择您自己的数字。
  2. Think of a pattern that is unlikely to occur in a filename like 'file-_-1'. And make the new file suffix the value of the array count(). You might miss an index this way but it is faster.
于 2012-11-14T19:31:52.117 回答