我正在为我在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);
}
我尝试使用GetRandomFileName方法,但是没有运气。不知道这是否是正确的方法。
提前致谢!
您可以使用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";
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句