2014-12-04 36 views
0

我在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數據,但我不知道如何實現這一點!

提前致謝!

+0

你需要ŧ將圖像數據作爲「Convert.ToBase64String(image_bytes)」(即,一個字符串) – 2014-12-04 17:49:45

回答

2

爲了使用<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); 
+0

如果我已經有字節數組了?我只是跳過imageConverter步驟,並將其轉換爲Base64?謝謝!!! – 2014-12-04 18:11:54

+0

那麼答案是肯定的,你只需跳到'Convert.ToBase64String(resourceByteArray);'答案的一部分。 – Dalorzo 2014-12-04 18:18:12