2015-05-17 74 views
0

我期待爲我在MVC 4 Web App中上傳的圖像生成一個隨機名稱。隨機圖像名稱圖像上傳MVC 4

我的控制器:

[HttpPost] 
[ValidateAntiForgeryToken] 
[ValidateInput(false)] 
public ActionResult Create(Article article, HttpPostedFileBase file) 
{ 
    if (ModelState.IsValid) 
    { 
     if (file != null && file.ContentLength > 0) 
     { 
      // extract only the filename 
      var fileName = System.IO.Path.GetFileName(file.FileName); 
      // store the file inside ~/App_Data/uploads folder 
      var path = System.IO.Path.Combine(Server.MapPath("~/UploadedImages/Articles"), fileName); 
      file.SaveAs(path); 
      article.ArticleImage = file.FileName; 
      ViewBag.Path = String.Format("~/UploadedImages/Events", fileName); 
     } 
     db.Articles.Add(article); 
     db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 

    ViewBag.SportID = new SelectList(db.Sports, "SportID", "Name", article.SportID); 
    return View(article); 
} 

我一直在使用GetRandomFileName方法,但沒有運氣嘗試。不知道這是否是正確的做法。

在此先感謝!

+0

你能更具體嗎?如果我做undestand:你想保存一個文件,但你不想重複?爲什麼不使用'DateTime.Ticks'或'Guid.NewGuid()'來爲文件名加前綴? – annemartijn

回答

2

可以使用Guid.NewGuid()生成隨機的名字,但是這裏是我在我的項目中使用的擴展方法:

public static string UploadFile(HttpPostedFileBase file) 
     { 
      if (file != null) 
      { 
       var fileName = Path.GetFileName(file.FileName); 
       var rondom = Guid.NewGuid() + fileName; 
       var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/Files/"), rondom); 
       if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/Content/Files/"))) 
       { 
        Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/Content/Files/")); 
       } 
       file.SaveAs(path); 

       return rondom; 
      } 
      return "nofile.png"; 
     } 
+1

正是我在找的。謝謝。 –

4

最簡單的方法可能是使用Guid.NewGuid()作爲文件名。 對於大多數用途而言,它足夠隨機,足夠獨特,創建之前創建的Guid的機會非常低。
您需要使用Path的GetExtension法提取原始文件名的文件擴展名,和前面提到的那個非常低的機會,我會建議寫這樣的方法:

string GenerateFileName(string TergetPath, HttpPostedFileBase file) 
{ 
    string ReturnValue; 
    string extension = Path.GetExtension(file.FileName); 
    string FileName = Guid.NewGuid().ToString(); 
    ReturnValue = FileName + extension; 
    if(!File.Exists(Path.Combine(TergetPath, ReturnValue)) 
    { 
     return ReturnValue; 
    } 
    // This part creates a recursive pattern to ensure that you will not overwrite an existing file 
    return GenerateFileName(TergetPath, file); 
} 

然後你可以叫它從這樣的現有代碼:

var DirectoryPath = Server.MapPath("~/UploadedImages/Articles"); 
var path = GenerateFileName(DirectoryPath, file);