2012-01-12 85 views
1

我寫了這個:ASP.net上傳文件,重命名,如果存在

protected void btnup_Click(object sender, EventArgs e) 
{ 
    if (ASPxUploadControl1.HasFile) 
    { 
     try 
     { 
      string filename = Path.GetFileName(ASPxUploadControl1.FileName); 
      ASPxUploadControl1.SaveAs(Server.MapPath("upload/") + filename); 
      StatusLabel.Text = "Upload status: File uploaded!"; 
     } 
     catch (Exception ex) 
     { 
      StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message; 
     } 
    } 
} 

問題是,如果我已經有File1.jpg,它將如果有人上傳File1.jpg覆蓋它。

在這裏做什麼?

+0

什麼是真正的問題?你可以檢查FileExist嗎?首先或者你不能連接用戶與文件? – Aristos 2012-01-12 11:39:58

回答

5

這裏你可以做什麼使服務器上的文件名唯一,以避免覆蓋。

if (ASPxUploadControl1.HasFile) 
{ 
    try 
    { 
     string extension = Path.GetExtension(ASPxUploadControl1.FileName); 
     string id = Guid.NewGuid().ToString(); 
     string fileLocation = string.Format("{0}/{1}{2}", 
              Server.MapPath("upload/"), 
              id, extension); 
     ASPxUploadControl1.SaveAs(fileLocation); 
     StatusLabel.Text = "Upload status: File uploaded!"; 
    } 
    catch (Exception ex) 
    { 
     StatusLabel.Text = "Upload status: The file could not be uploaded. " 
          + "The following error occured: " + ex.Message; 
    } 
} 
3

當您撥打ASPxUploadControl1.SaveAs時,assign是一個唯一的名稱。例如,內容的運行編號/ GUID/MD5散列。無論你認爲合適。

我發現它是最簡單的創建一個使用新的GUID字符串:System.Guid.NewGuid().ToString()

1

你必須給文件名unique名。
DB序列或靜態運行編號變量可能適合您。

您可以使用一個隨機的唯一GUID字符串,請參閱this MSDN文章

1

我建議你使用GUID當您保存在Web應用程序文件,以避免這個問題,我通常使用:

Guid.NewGuid().ToString().Replace("-", "").ToUpper() 

作爲文件名。

0
protected void btnup_Click(object sender, EventArgs e) 
     { 
      if (ASPxUploadControl1.HasFile) 
      { 
       try 
       { 
        string ext = Path.GetExtension(ASPxUploadControl1.FileName); 
        string filename = DateTime.Now.Ticks.ToString()+ext; 
        ASPxUploadControl1.SaveAs(Server.MapPath("upload/") + filename); 
        StatusLabel.Text = "Upload status: File uploaded!"; 
       } 
       catch (Exception ex) 
       { 
        StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message; 
       } 
      } 
    }