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

时间:2017-09-25 10:55:52

标签: c# asp.net-mvc asp.net-mvc-4

我想使用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 个答案:

答案 0 :(得分:2)

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