【问题标题】:Retrieve binary data from C# with Ajax使用 Ajax 从 C# 检索二进制数据
【发布时间】:2014-12-05 01:49:42
【问题描述】:

我在网络开发方面有点新手,我无法实现我想要做的事情。

我有一个数据库,其中包含一个名为“PI_Banners”的表,其中存储了一些图像。此表存储一个 ID 和一个包含图像二进制数据的 VARBINARY 列。

我正在尝试做的是通过对 C# 函数的 Ajax 请求检索该数据,并使用数据 URI 方案创建一个“img”标签。然后将该新图像附加到 div

这是我得到的:

Ajax 调用:

$(document).ready(function() {

    var dto = {};
    var dtoJSON = JSON.stringify(dto);

    $.ajax({
        async: false,
        url: 'BannerRotativo.aspx/devuelveBanners',
        cache: false,
        dataType: 'json',
        type: "POST",
        data: dtoJSON,
        contentType: "application/json; charset=utf-8",
        success: function(data, textStatus, jqXHR) {
            responsedevuelveBanners(data);
        },
        error: errorResponse
        });
});

成为 C# 函数的“devuelveBanner”。

C# 代码:

public static string devuelveBanners()
{
    DataReader DR;
    DR = listaBanners();
    //armaJson creates the Json string from the DataReader.
    string strJson = GENERAL.armaJson(DR);
    return strJson;
}


public DataReader listaBanners()
    {
        try
        {
            string strComando;
            sqlCommand SQLC;
            DataReader DR;

            strComando = "SELECT banner_img FROM PI_Banners";
            //sqlCon is the connection, and is open already.
            SQLC = new System.Data.SqlClient.SqlCommand(strComando, sqlCon);
            SQLC.CommandType = CommandType.Text;
            DR = SQLC.ExecuteReader();

            return DR;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

当我解析 Json 字符串并创建图像时:

function responsedevuelveBanners(data)
    {
        var datos = JSON.parse(data.d);
        $("#imgContainer").append("<img src='data:image/jpg;base64," + datos.Rows[0].Row[0].banner_img + "' />");
    }

图像已创建但未显示,因为它具有以下 URL:

data:image/jpg;base64,System.Byte[]

我知道我在尝试以这种方式检索 json 数据时做错了什么,但我不知道如何实现这一点!

提前致谢!

【问题讨论】:

  • 需要将图片数据返回为Convert.ToBase64String(image_bytes)(即字符串)

标签: javascript c# jquery


【解决方案1】:

为了使用&lt;img src="data:image/PNG;base64' base64 部分是因为您需要返回一个Base64 字符串而不是字节数组,因此您需要将您的byte[] 转换为64Base 使用:Convert.ToBase64String(buffer)

所以以你的代码为例:

ImageConverter imageConverter = new ImageConverter();
byte[] resourceByteArray = (byte[])imageConverter.ConvertTo(_YourObj.GetImage(), typeof(byte[]));

您的 WebApi 方法应该返回:

return Convert.ToBase64String(resourceByteArray);

【讨论】:

  • 如果我已经有了字节数组怎么办?我只是跳过 imageConverter 步骤并将其转换为 Base64?谢谢!!!
  • 答案是肯定的,您只需跳到答案的Convert.ToBase64String(resourceByteArray); 部分即可。
猜你喜欢
  • 1970-01-01
  • 2012-02-23
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
  • 2014-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多