使用 Ajax 从 C# 检索二进制数据

Retrieve binary data from C# with Ajax

本文关键字:二进制 数据 检索 Ajax 使用      更新时间:2023-09-26

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

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

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

这就是我得到的:

阿贾克斯调用:

$(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
        });
});

作为 "devuelveBanners" 的 C# 函数。

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 数据时犯了非常错误,但我不知道如何实现这一点!

提前感谢!

为了使用<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);