我已经浏览了这个网站上几乎所有的帖子,似乎都涉及图像上传和持久化到 SQL Server 数据库,但是,我正在做的事情仍然不正确。
图像未正确保存或从数据库正确提取,因为在写入/检索字节时图像无效。比较上传的图像与原始图像的大小时,大小不同(更大)?
型号:
public byte[] Photo { get; set; }
public string PhotoMimeType { get; set; }
public string PhotoName { get; set; }
Sql Server:
[PhotoMimeType] [nvarchar](50) NULL,
[PhotoName] [nvarchar](50) NULL,
[Photo] [image] NULL,
在 Controller 中,我有以下内容来保存图像:
public ActionResult Edit(AgentInfo modifiedAgent, HttpPostedFileBase postedFile)
{
if(ModelState.IsValid)
{
var model = _agentRepository.GetByID(modifiedAgent.AgentID);
if (TryUpdateModel(model))
{
if (postedFile != null)
{
int imageLength = postedFile.ContentLength;
byte[] imgBytes = new byte[imageLength];
postedFile.InputStream.Read(imgBytes, 0, imageLength);
model.PhotoMimeType = postedFile.ContentType;
model.PhotoName = postedFile.FileName;
model.Photo = imgBytes;
}
_agentRepository.Save(model);
return RedirectToAction("ManageAgents", "Agent");
}
}
return View("Edit", modifiedAgent);
}
检索:
[HttpGet]
public ActionResult GetImage(int id)
{
var agent = _agentRepository.GetByID(id);
return File(agent.Photo, agent.PhotoMimeType, agent.PhotoName);
}
显示:
<img src='@Url.Action("GetImage", "Agent", new { id = Model.AgentID })' />
编辑:
好吧,在思考这是我如何将这些连接在一起的问题之后,结果是我的数据库映射......frick
仅供引用,当使用 Fluent-nhibernate 进行映射并且想要保存图像字节时,sql 数据类型为 varbinary(max),映射如下:
Map(x => x.Photo).Column("Photo").Length(2147483647).CustomSqlType("varbinary(MAX)");
最佳答案
在读取输入流之前尝试倒带它:
postedFile.InputStream.Position = 0;
或使用临时MemoryStream
:
using (var memoryStream = new MemoryStream())
{
postedFile.InputStream.CopyTo(memoryStream);
model.Photo = memoryStream.ToArray();
}
关于asp.net-mvc - 在 asp.net MVC 中保存/显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9605358/