2011-03-06 84 views
2

我想保留上傳的文件名,以便用戶可以使用相同的名稱下載文件。但我該如何執行它?我看到的一個選項是將每個文件存儲到具有唯一名稱的文件夾(例如GUID)。任何其他選項?ASP.NET保存上傳的文件名

回答

1

我覺得GUID是更好的選擇,但我們通常在辦公室DateTime

5

當一個文件被上傳您可以提取其名稱中使用:

[HttpPost] 
public ActionResult Index(HttpPostedFileBase file) 
{ 
    if (file != null && file.ContentLength > 0) 
    { 
     // Get the filename of the uploaded file 
     var fileName = Path.GetFileName(file.FileName); 
     var savedFilename = Guid.NewGuid().ToString(); 

     // TODO: Associate the fileName with the savedFilename 
     // and probably the currently connected user in the database 

     // Save the file inside the Uploads folder 
     var path = Path.Combine(Server.MapPath("~/Uploads"), savedFilename); 
     file.SaveAs(path); 
    } 
    return RedirectToAction("Index"); 
} 

您可以在磁盤上的文件存儲在某些唯一的名稱(一個GUID是一個很好的選擇),然後將這個唯一的名字與實際的文件名和用戶相關聯,以便稍後當他想要下載文件時,您將擁有該映射。

+0

這不是他的問題;例如,如果有人上傳文件的文件名爲abc.jpg,其他用戶也上傳相同的文件名,那麼將出現問題 – 2011-03-06 09:59:41

+0

@Muhammad Akhtar,是的,你是正確的。 – 2011-03-06 10:00:31

+0

再次你編輯了你的答案,我想你再次誤解了這個問題。他想要的是,如果用戶上傳文件的名稱爲abc.jpg,之後如果要下載,他將使用相同的名稱。 – 2011-03-06 10:10:00