Alex Snigirev
Alex Snigirev

Reputation: 67

How generate a unique file name at upload files in webserver (MVC)

a have markup

     <div>
        @using (Html.BeginForm("Upload","Resume", FormMethod.Post, new { enctype = "multipart/form-data" }))
        { @Html.AntiForgeryToken() <fieldset> <legend>Download Resume</legend> <div class="editor-field">
         @Html.TextBox("file", "", new { type = "file" }) </div> <div class="editor-field"> 
        <input type="submit" value="Upload" style="width: 120px; height: 25px; font-size: 1.1em; padding:0" />
         </div> </fieldset> }
    </div>

and Controller:

      [HttpPost]
    public ActionResult Upload(HttpPostedFileBase file) 
    { 
        try 
        { 
            if (file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/uploads"), fileName); file.SaveAs(path); 
            } 
            ViewBag.Message = "SuccessUpload";
            return RedirectToAction("SuccessUpload", "Resume");
        } catch 
        { ViewBag.Message = "Fail"; 
            return RedirectToAction("Upload"); } 
    } 

How can generate unique file name at upload files, thanks for answers!

Upvotes: 2

Views: 9507

Answers (2)

Ashwini Verma
Ashwini Verma

Reputation: 7525

One of the way is to concate current date.

var fileName = DateTime.Now.ToString("yyyymmddMMss") + System.IO.Path.GetExtension(file.FileName);

Upvotes: 6

AliRıza Adıyahşi
AliRıza Adıyahşi

Reputation: 15866

// change file name with its extension
var fileName = Guid.NewGuid().ToString() + 
    System.IO.Path.GetExtension(file.FileName);

var uploadUrl = Server.MapPath("~/uploads");

file.SaveAs(Path.Combine(uploadUrl, fileName));

Upvotes: 9

Related Questions