2

我是 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 对象始终为空。我的逻辑中是否有任何流程(除了之后发生的所有转换,我知道它们很混乱)还是有任何其他方法可以解决这个问题?

4

2 回答 2

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!" />
}

和 Action 方法

[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();
}
于 2012-08-21T15:46:35.033 回答
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>
于 2012-08-21T15:45:17.257 回答