开发者

Get binary from uploaded file (image) in ASP.NET MVC

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 fil开发者_StackOverflow中文版e) {

  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?


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜