asp.net-mvc - 在 asp.net MVC 中保存/显示图像

标签 asp.net-mvc asp.net-mvc-3 image file-upload

我已经浏览了这个网站上几乎所有的帖子,似乎都涉及图像上传和持久化到 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/

相关文章:

html - 保留链接 a :active the same way after link press

asp.net-mvc - 一起使用 ASP.Net MVC 和 node.js

c# - 使用 MVC 和 Web API 的 Ng-File-Upload - 不断获取 "404 Not Found"

javascript - 如何在 Orchard CMS 中使用 javascript(js 文件)

java - 如何利用遗传算法减少噪声图像的误差?

javascript - 使用javascript获取位图的像素

javascript - 为 MVC 中的不同 View 加载单独的 javascript

asp.net-mvc - 未将对象引用设置为 TempData 中对象的实例

asp.net - 通过长轮询检查数据库的变化

c# - 在编程中处理属性