我在Web開發中有點新,我無法實現我想要做的。從C#用Ajax檢索二進制數據
我有一個名爲「PI_Banners」表的數據庫,我在那裏存儲一些圖像。該表存儲包含圖像的二進制數據的ID和VARBINARY列。
我想要做的是將數據與Ajax請求檢索到一個C#函數,並使用數據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 + "' />");
}
圖像被創建,但顯示不出來,因爲它有此網址:
data:image/jpg;base64,System.Byte[]
我知道我在做一些非常錯誤的事情t試圖以這種方式檢索json數據,但我不知道如何實現這一點!
提前致謝!
你需要ŧ將圖像數據作爲「Convert.ToBase64String(image_bytes)」(即,一個字符串) – 2014-12-04 17:49:45