.NET MVC存儲圖片到數據庫的解決方案

步驟:

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(int studentId)
        {
            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="" />

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章