Ivin Raj
Ivin Raj

Reputation: 3429

How to pass ID to image file name using MVC?

I want to save my image File using session ID value and then in the uploads folder I want to pass the ID value like 3.jpeg or png

[HttpPost]
        public ActionResult AddImage(HttpPostedFileBase postedFile)
        {
            int compId = Convert.ToInt32(Session["compID"]);
            if (postedFile != null)
            {
                string path = Server.MapPath("~/Uploads/");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                postedFile.SaveAs(path + Path.GetFileName(postedFile.FileName));
                ViewBag.Message = "File uploaded successfully.";
            }

            return RedirectToAction("AddCompany");
        }

Below i have attached the image

ID

Upvotes: 0

Views: 791

Answers (1)

Clive Ciappara
Clive Ciappara

Reputation: 558

When saving your image, you need to combine the compId and the file extension as follows:

    var filename = compId.ToString() + Path.GetExtension(postedFile.FileName);

So your code should look something like this:

    [HttpPost]
    public ActionResult AddImage(HttpPostedFileBase postedFile)
    {
        int compId = Convert.ToInt32(Session["compID"]);
        if (postedFile != null)
        {
            string path = Server.MapPath("~/Uploads/");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var filename = compId.ToString() + Path.GetExtension(postedFile.FileName);
            postedFile.SaveAs(path + filename);
            ViewBag.Message = "File uploaded successfully.";
        }

        return RedirectToAction("AddCompany");
    }

Upvotes: 2

Related Questions