简体   繁体   中英

Random image name image upload MVC 4

I am looking to generate a random name for the image that I upload in my MVC 4 Web App.

My Controller:

[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);
}

I have tried using GetRandomFileName method but with no luck. Not sure if this is the right way to do it.

Thanks in advance!

The simplest way is probably to use Guid.NewGuid() as the file name. It's pseudo random enough for most purposes and unique enough to have very low chances of creating a Guid that was created before.
You will need to extract the file extension from the original file name using Path's GetExtension method, and for that very low chances mentioned earlier, I would suggest writing a method like this:

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); 
}

Then you can call it from your existing code like this:

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

You can use Guid.NewGuid() for generating random names, However here is an extension method that I use in my projects:

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";
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM