.NET MVC儲存圖片到資料庫的解決方案
阿新 • • 發佈:2020-07-31
步驟:
1. 設定資料庫欄位型別為: image(注意同時設定字串型別的欄位儲存圖片類別)
2. 在Conroller中,增加如下方法分別用於上傳和前端獲取
表單上傳:
[HttpPost] public ActionResult Create(Student student, HttpPostedFileBase image) { if (ModelState.IsValid) { if (image != null) {//Define a limited bype[] variable.byte[] imageData = new byte[image.ContentLength]; //Read the image data to byte[] variable.image.InputStream.Read(imageData, 0, image.ContentLength); //Sampele(I have added two column with 'StudentPictureData' and 'StudentPictureType')student.StudentPictureData = new Binary(imageData); student.StudentPictureType = image.ContentType; ...SaveChanges to DB... } } return RedirectToAction("Index"); }
前端呼叫進行顯示:
public FileContentResult GetImage(intstudentId) { Student student = repository.Students.FirstOrDefault(c => c.Id == studentId); if (prod != null) { return File(student.StudentPictureData.ToArray(), student.StudentPictureType); } else { return null; } }
3. 在View中通過如下方式展示圖片
<img src="@Url.Action("GetImage","Student",new { @item.Id})" width="100" height="100" alt="" />