views:

35

answers:

1

I'm using the following code:

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

  <label for="file">Filename:</label>
  <input type="file" name="file" id="file" />

  <input type="submit" />
</form>

And...

[HttpPost]
public ActionResult Index(HttpPostedFileBase file) {

  if (file.ContentLength > 0) {
    var fileName = Path.GetFileName(file.FileName);
    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
    file.SaveAs(path);
  }

  return RedirectToAction("Index");
}

Instead of saving the file to the filesystem, I want to extract the binary data from the incoming file so I can commit the image to my database. What changes can I make to my code to support this?

+1  A: 

Perhaps try this snippet in your solution:

byte[] imgData;
using (BinaryReader reader = new BinaryReader(file.InputStream)) {
   imgData = reader.ReadBytes(file.InputStream.Length);
}

//send byte array imgData to database, or use otherwise as required.
p.campbell