我对网络开发有点陌生,我无法实现我想要做的事情。
我有一个数据库,其中有一个名为“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
});
});
成为“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);
关于javascript - 使用 Ajax 从 C# 检索二进制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27300558/