-1

View:

@using (Html.BeginForm("AddDetails", "UsersDetails", null,
                FormMethod.Post, new
                {
                    encrypt = "multipart/form-data",
                    @class = "form-horizontal",
                    role = "form"
                }))
{ 
    @Html.AntiForgeryToken()
    <label for="Picture">Upload Image:</label>
    <input name="Picture" id="Picture" type="file" />
}

Controller action:

public ActionResult AddDetails(UsersDetailViewModel udv, FormCollection fc, HttpPostedFileBase file)
{
    if (file != null && file.ContentLength > 0)
        try
        {
            string path = Path.Combine(Server.MapPath("~/Uploads"),
                                       Path.GetFileName(file.FileName));
            file.SaveAs(path);
            ViewBag.Message = "File uploaded successfully";
        }
        catch (Exception ex)
        {
            ViewBag.Message = "ERROR:" + ex.Message.ToString();
        }
    else
    {
        ViewBag.Message = "You have not specified a file.";
    }

    ud.Picture = udv.Picture;

    return View();
}

When I try to upload image then in upload input box it contain the whole path as c:\users\Adi\black.png but I need only image name as black image.

Ilya Chumakov
  • 23,161
  • 9
  • 86
  • 114

1 Answers1

0

Path.GetFileName will you the file name with extension (Ex :"black.png").

if (file != null && file.ContentLength > 0)
{
   var fileName= Path.GetFileName(file.FileName);
   // It's a good idea to remove spaces
   fileName=fileName.Replace(" ","_");
   //If you want to generate a unique filename, you may try something like
   // fileName=Guid.NewGuid().ToString+fileName;

   var path = Path.Combine(Server.MapPath("~/Uploads"),fileName);
   file.SaveAs(path);

   //you can use fileName value to save to user record.
}
Shyju
  • 214,206
  • 104
  • 411
  • 497