You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC视图中图片无法显示问题求助

问题:ASP.NET Core视图中无法显示从SQL Server读取的图片

我尝试在视图中显示图片,操作步骤如下:

  1. 已通过如下SQL语句将图片插入SQL Server Express(price定义为int类型,picture为varbinary(MAX)类型):
insert into products (price, picture) 
    select 499, BulkColumn 
    from Openrowset(Bulk 'C:\Users\tally\Pictures\harddisk-275-183.jpg', Single_Blob) as img
  1. 定义了如下模型属性:
public class ProductsModel
{
    public Image ProductImage { get; set; }
    public int ProductPrice { get; set; }
}
  1. 通过如下控制器方法从数据库获取数据:
[HttpGet]
public IActionResult Products(ProductsModel objProductsModel)
{
    string conStr = "Data Source=.\\SQLEXPRESS; Initial Catalog=Onlineproducts; Integrated Security=True";

    SqlConnection con = new SqlConnection(conStr);
    con.Open();

    SqlDataAdapter dataAdapter = new SqlDataAdapter(new SqlCommand("select * from products", con));
    DataSet dataSet = new DataSet();
    dataAdapter.Fill(dataSet);

    if (dataSet.Tables[0].Rows.Count == 1)
    {
        Byte[] data = new Byte[0];
        data = (Byte[])(dataSet.Tables[0].Rows[0]["picture"]);
        MemoryStream mem = new MemoryStream(data);
        objProductsModel.ProductImage = Image.FromStream(mem);

        objProductsModel.ProductPrice = Convert.ToInt32(dataSet.Tables[0].Rows[0]["price"]);
        return View(objProductsModel);
    }

    return View(objProductsModel);
}
  1. 在视图中尝试显示图片和价格:
@model Nettbutikk.Models.ProductsModel

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link rel="stylesheet" href="~/css/products.css" />
</head>
<body>
    <p><h1>Products</h1></p>
    <hr />

        <div class="responsive">
            <div class="gallery">

                <div>@Html.DisplayFor(ProductsModel => ProductsModel.ProductImage)</div>

                <div class="desc">Kr @Html.DisplayFor(ProductsModel => ProductsModel.ProductPrice)</div>
            </div>
        </div>
    </body>
</html>

目前价格可正常显示,但图片无法展示,是否应使用DisplayFor以外的方法?


解决方案

是的,不能直接用@Html.DisplayFor展示.NET的Image对象,HTML无法直接识别该类型。推荐两种可行方案:

方案一:将图片转为Base64字符串直接展示

1. 修改模型

把ProductImage替换为存储Base64字符串的属性:

public class ProductsModel
{
    public string ProductImageBase64 { get; set; }
    public int ProductPrice { get; set; }
}

2. 修改控制器逻辑

读取二进制图片数据后转为Base64格式(注意根据图片实际格式修改image/jpeg):

[HttpGet]
public IActionResult Products(ProductsModel objProductsModel)
{
    string conStr = "Data Source=.\\SQLEXPRESS; Initial Catalog=Onlineproducts; Integrated Security=True";

    using (SqlConnection con = new SqlConnection(conStr))
    {
        con.Open();
        SqlDataAdapter dataAdapter = new SqlDataAdapter(new SqlCommand("select * from products", con));
        DataSet dataSet = new DataSet();
        dataAdapter.Fill(dataSet);

        if (dataSet.Tables[0].Rows.Count == 1)
        {
            byte[] imageData = (byte[])dataSet.Tables[0].Rows[0]["picture"];
            objProductsModel.ProductImageBase64 = $"data:image/jpeg;base64,{Convert.ToBase64String(imageData)}";
            objProductsModel.ProductPrice = Convert.ToInt32(dataSet.Tables[0].Rows[0]["price"]);
        }
    }
    return View(objProductsModel);
}

3. 修改视图

用<img>标签直接引用Base64字符串:

<div><img src="@Model.ProductImageBase64" alt="Product Image" /></div>

方案二:创建单独接口返回图片流

1. 修改模型

新增ProductId(需确保表中有主键字段),移除Image类型属性:

public class ProductsModel
{
    public int ProductId { get; set; }
    public int ProductPrice { get; set; }
}

2. 添加返回图片的控制器方法

[HttpGet]
public IActionResult GetProductImage(int productId)
{
    string conStr = "Data Source=.\\SQLEXPRESS; Initial Catalog=Onlineproducts; Integrated Security=True";
    byte[] imageData = null;

    using (SqlConnection con = new SqlConnection(conStr))
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("select picture from products where id = @Id", con);
        cmd.Parameters.AddWithValue("@Id", productId);
        imageData = cmd.ExecuteScalar() as byte[];
    }

    if (imageData == null)
        return NotFound();

    // 根据图片实际格式修改Content-Type
    return File(imageData, "image/jpeg");
}

3. 修改视图

通过<img>标签调用该接口(替换YourControllerName为实际控制器名称):

<div><img src="@Url.Action("GetProductImage", "YourControllerName", new { productId = Model.ProductId })" alt="Product Image" /></div>

内容的提问来源于stack exchange,提问作者javed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 16:25:57