代码之家  ›  专栏  ›  技术社区  ›  Ivin Raj

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

  •  0
  • Ivin Raj  · 技术社区  · 7 年前

    我想用 session ID 上载 我想传递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");
            }
    

    ID

    1 回复  |  直到 7 年前
        1
  •  2
  •   Clive Ciappara    7 年前

    保存图像时,需要按如下方式组合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");
        }