我想从SQL服务器数据库上载和检索图像。我创建了模型,控制器和视图如下。图像不显示在视图中ASP.NET MVC
视图模型是非常相似,实际的模态
CheckoutModel.cs
public class CheckOutViewModel
{
public int ID { get; set; }
public ApplicationUser CandidateId { get; set; }
[Required]
public byte[] Image { get; set; }
}
此外,我创建控制器上传并显示与操作方法即索引图像,创建和retreive
Index方法用于显示图像,create方法用于将图像上传和保存到数据库中,并使用检索方法根据图像的id查询图像。
CheckOutController.cs
using Microsoft.AspNet.Identity;
using shanuMVCUserRoles.Repositories;
using shanuMVCUserRoles.ViewModels;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace shanuMVCUserRoles.Models
{
public class CheckOutController : Controller
{
private readonly ApplicationDbContext db;
public CheckOutController()
{
db = new ApplicationDbContext();
}
[Route("Index")]
[HttpGet]
public ActionResult Index()
{
var content = db.Checkouts.Select(s => new
{
s.ID,
s.CandidateId,
s.Image,
});
List<CheckOutViewModel> contentModel = content.Select(item => new CheckOutViewModel()
{
ID = item.ID,
CandidateId = item.CandidateId,
Image = item.Image,
}).ToList();
return View(contentModel);
}
public ActionResult RetrieveImage(int id)
{
byte[] cover = GetImageFromDataBase(id);
if (cover != null)
{
return File(cover, "image/jpg");
}
else
{
return null;
}
}
public byte[] GetImageFromDataBase(int Id)
{
var q = from temp in db.Checkouts where temp.ID == Id select temp.Image;
byte[] cover = q.First();
return cover;
}
// GET: CheckOut
[Authorize]
public ActionResult Create()
{
return View();
}
[Route("Create")]
[HttpPost]
public ActionResult Create(CheckOutViewModel model)
{
HttpPostedFileBase file = Request.Files["ImageData"];
CheckOutRepository service = new CheckOutRepository();
int i = service.UploadImageInDataBase(file, model);
if (i == 1)
{
return RedirectToAction("Index");
}
return View(model);
}
}
}
然后创建了一个存储库文件夹保存图像和字段在数据库并且还用于转换的图像,以字节的方法。
CheckoutRepostiory.cs
public class CheckOutRepository
{
private readonly ApplicationDbContext db;
public CheckOutRepository()
{
db = new ApplicationDbContext();
}
public int UploadImageInDataBase(HttpPostedFileBase file, CheckOutViewModel contentViewModel)
{
contentViewModel.Image = ConvertToBytes(file);
var userId = HttpContext.Current.User.Identity.GetUserId();
var member = db.Users.Single(u => u.Id == userId);
var Content = new CheckOut
{
CandidateId = member,
Image = contentViewModel.Image
};
db.Checkouts.Add(Content);
int i = db.SaveChanges();
if (i == 1)
{
return 1;
}
else
{
return 0;
}
}
public byte[] ConvertToBytes(HttpPostedFileBase image)
{
byte[] imageBytes = null;
BinaryReader reader = new BinaryReader(image.InputStream);
imageBytes = reader.ReadBytes((int)image.ContentLength);
return imageBytes;
}
}
此外,我创建的索引视图,然后我使用对于每个环放置在图像中的图像标记。
Index.cshtml
@foreach (var item in Model)
{
<tr>
<td>
<img src="/Content/RetrieveImage/@item.ID" alt="" height=100 width=200 />
</td>
</tr>
}
你需要给图片路径代替了src中的@ item.ID。在下面检查我的答案。 –
你能举个例子吗? –
查看下面的答案。 –