如何使用 MVC 将 ID 传递给图像文件名?

How to pass ID to image file name using MVC?

我想使用 session ID 值保存我的图像文件,然后在 uploads 文件夹中我想传递 ID 值,例如 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");
        }

下面我附上了图片

保存图片时,需要将compId和文件扩展名组合如下:

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

因此您的代码应如下所示:

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