.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="" />

 

posted @ 2020-07-31 18:39  【舍予】  阅读(599)  评论(0编辑  收藏  举报