如何从HDD获取文件到Bitmap对象[ASP MVC 3]?

时间:2012-08-21 15:37:34

标签: asp.net-mvc

我是ASP MVC的新手,我一直在尝试将位图文件从硬盘上传到C#Bitmap对象,我稍后将其分配给我的模型。

视图(cshtml文件)如下所示:

    <form action = "DisplayAddedPicture" method=post>
    <input type=file name="Picture" id = "Picture"/>
    <input type=submit value="Send!" />
    </form>

来自控制器的DisplayAddedPicture方法:

        [HttpPost]
        public ActionResult DisplayAddedPicture()
        {
          HttpPostedFileBase File = Request.Files["Picture"];

          if (File == null) throw new Exception("NullArgument :( ");

          // file stream to byte[]
          MemoryStream target = new MemoryStream();
          File.InputStream.CopyTo(target);
          byte[] TempByteArray = target.ToArray();

          // byte[] to Bitmap
          ImageConverter imageConverter = new ImageConverter();
          Image TempImage = (Image)imageConverter.ConvertFrom(TempByteArray);
          Bitmap FinalBitmap = new Bitmap(TempImage);

          // (...)
        }

事实证明,每次我得到的都是异常,因为HttpPostedFileBase对象始终为null。在我的逻辑中是否存在任何流动(除了之后发生的所有转换,我知道它们是混乱的)或者还有其他方法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

试试这个

在您的视图中,

@using (Html.BeginForm("DisplayAddedPicture", "YourControllerName", 
                      FormMethod.Post, new { enctype = "multipart/form-data" }))
{
     <input type=file name="Picture" id = "Picture"/>
     <input type=submit value="Send!" />
}

动作方法

[HttpPost] 
public ActionResult DisplayAddedPicture(HttpPostedFileBase Picture)
{
  if (Picture!= null && Picture.ContentLength > 0) 
  {
      //Do some thing with the Picture object
      //try to save the file here now.
      //After saving follow the PRG pattter (do a redirect)

      //return RedirectToAction("Uploaded");
  }  
  return View();
}

答案 1 :(得分:0)

尝试将以下内容添加到表单标记中:enctype="multipart/form-data"

<form method="post" action="DisplayAddedPicture" enctype="multipart/form-data">

    <input type=file name="Picture" id = "Picture"/>
    <input type=submit value="Send!" />

</form>