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

吃可爱长大的小学妹 提交于 2019-12-13 03:46:25

问题


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.


来源:https://stackoverflow.com/questions/3947154/get-binary-from-uploaded-file-image-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!