2017-09-25 34 views
0

我要保存使用session ID值,然后在上传文件夹我想图像如何使用MVC将ID传递给图像文件名?

ID

+0

而你的问题是什么? – OctoCode

+0

我的问题是这样的..保存到文件夹3.jpeg或png @ OctoCode –

+0

因为我认为简单的解决方案是'postingFile.SaveAs(path + compId.ToString()+ System.IO.Path.GetExtension(postingFile.FileName) );' – mmushtaq

回答

2
传似 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值,下面我附上我的图片文件

保存图片时,您需要将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"); 
    } 
+0

我认为这段代码使得文件名像3MyPic.jpeg,但是他想将MyPic.jpeg保存为3.jpeg。 –

+1

实际上,它只会从文件名获得扩展名,而不是使用** Path.GetExtension **获得整个文件名,因此最终名称将是compId加上文件扩展名 –

+0

我忽略了Path.GetExtension。谢谢。 –