2012-11-14 18 views
0

我正在嘗試處理重複的文件名。如果用戶上傳名爲「文件」的文件名,則另一用戶上載名爲「文件」的文件,我希望能夠將1添加到新文件中,因此現在將其稱爲「1file」。我能夠做到這一點,但我的問題是當有人第三次上傳「文件」它覆蓋「1文件」我需要增加1。我使用Yii框架將值添加到文件的末尾(如果它在php中重複)

這是我在我的控制器功能:

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

}

+1

爲什麼不重命名文件一個唯一的ID並將真實姓名存儲在數據庫中? –

+0

+1用於重命名的獨特文件名,如果您需要真名,您可以隨時在UI中顯示任何內容,甚至可以用原始名稱「下載」文件 – Asgaroth

回答

1

嗯,我認爲你有兩個選擇:

  • 追加類似microtime()到文件名末尾,這樣,它幾乎是不可能讓你有相同的文件名兩次。

  • ,如果你需要的文件保存在爲了不想使用上面的方法,那麼你就必須在最後插入數字存儲在數據庫中,然後檢索它,增量和存儲再次。

我也使用YII框架,但不記得任何特定於Yii的東西,可以幫助你。

0

你將不得不通過那些可能匹配模式的所有文件進行掃描。

看看這裏爲如何找到使用通配符搜索文件:PHP file_exists and wildcard

從那裏,你做ACN兩件事情。

  1. 處理每個文件,讀取數字,然後選擇您自己的數字。
  2. 考慮一個不太可能出現在像'file -_- 1'這樣的文件名中的模式。並使新文件後綴數組count()的值。您可能會錯過索引,但速度更快。
相關問題