Get binary from uploaded file (image) in A

2019-09-06 08:31发布

问题:

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:

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.