Kamil T
Kamil T

Reputation: 2216

How to get file from HDD to Bitmap object [ASP MVC 3]?

I'm new to ASP MVC and I've been trying to upload a bitmap file from hard drive to a C# Bitmap object, which I would later assign to my Model.

The view (cshtml file) looks like this:

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

And the DisplayAddedPicture method from controller:

        [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);

          // (...)
        }

It turns out that every time all I get is an Exception, as the HttpPostedFileBase object is always null. Is there any flow in my logic (apart from all of those conversions which come afterwards, I know they're messy) or is there any other way to solve this?

Upvotes: 2

Views: 425

Answers (2)

Shyju
Shyju

Reputation: 218722

Try this

In your View,

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

And the Action method

[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();
}

Upvotes: 1

Dismissile
Dismissile

Reputation: 33071

Try adding the following to your form tag: 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>

Upvotes: 0

Related Questions