2017-09-25 60 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。謝謝。 –

相關問題