dk_*_*032 0 c# asp.net-mvc asp.net-mvc-4
我希望为我在MVC 4 Web App中上传的图像生成一个随机名称.
我的控制器:
[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);
}
Run Code Online (Sandbox Code Playgroud)
我尝试过使用GetRandomFileName方法,但没有运气.不确定这是否是正确的方法.
提前致谢!
最简单的方法可能是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);
}
Run Code Online (Sandbox Code Playgroud)
然后你可以从你现有的代码中调用它,如下所示:
var DirectoryPath = Server.MapPath("~/UploadedImages/Articles");
var path = GenerateFileName(DirectoryPath, file);
Run Code Online (Sandbox Code Playgroud)