2017-09-25 18 views
0

私はsession ID値を使用して、私の画像ファイルを保存すると、その後アップロードフォルダに私はMVCを使用して画像ファイル名にIDを渡すにはどうすればよいですか?

ID

+0

をそして、あなたの質問はありますか? – OctoCode

+0

私の質問はこのようです..フォルダ3.jpegまたはpng @ OctoCodeに保存 –

+0

私は単純な解決策は 'postedFile.SaveAs(path + compId.ToString()+ System.IO.Path.GetExtension(postedFile.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を見落としました。ありがとう。 –

関連する問題