![](/img/trans.png)
[英]Insert and retrieve BLOB image in SQLite with HTML5 and JavaScript
[英]Retrieve MySQL Image Blob in HTML
對於我的Web應用程序Im使用C#WebService,JavaScript,jQuery和JavaScript,我將圖像上傳到具有以下結構的表中:
Id | FileName | ContentType | Content
1 |Tulips.jpg| image/jpeg | (Binary/Image)
我想在HTML頁面中顯示此信息,此刻我的HTML顯示此信息:
2 | Tulips.jpg | image/jpeg | System.Byte[]
我想顯示圖像而不是System.Byte [],該怎么辦? 這是我的全部代碼:
C#類
公共類Imagenes {public Imagenes(){}
public Imagenes(int id, string fileName, string type, string content)
{
Id = id;
FileName = fileName;
Type = type;
Content = content;
}
public int Id { get; set; }
public string FileName { get; set; }
public string Type { get; set; }
public string Content { get; set; }
}
數據庫類
這里沒有問題,只是Select * from。
的WebMethod
[WebMethod]
public string Image(int id)
{
DataTable dt = new DataTable();
dt = conn.consultImg("tbl_images", id);
Imagenes img;
List<Imagenes> list = new List<Imagenes>();
for (int i = 0; i < dt.Rows.Count; i++)
{
img = new Imagenes();
img.Id = Convert.ToInt32(dt.Rows[i]["Id"]);
img.FileName = dt.Rows[i]["FileName"].ToString();
img.Type = dt.Rows[i]["ContentType"].ToString();
img.Content = dt.Rows[i]["Content"].ToString();
list.Add(img);
img = null;
}
JavaScriptSerializer js = new JavaScriptSerializer();
string lines = js.Serialize(list);
return lines;
}
和JavaScript代碼:
var id = $('#Id').val();
$.ajax({
type: "POST",
url: "ws_MyWebService.asmx/Image",
data: '{"id":' + id + '}',
dataType: 'json',
contentType: 'application/json',
timeout: 60000,
error: function (xhr) {
},
success: function (data) {
var aRC = JSON.parse(data.d);
var lines = "";
for (var i = 0; i < aRC.length; i++) {
var id = aRC[i].Id;
var fname = aRC[i].FileName;
var type = aRC[i].Type;
var content = aRC[i].Content;
lines += '<p>' + id + '</p>';
lines += '<p>' + fname + '</p>';
lines += '<p>' + type + '</p>';
lines += '<p>' + content + '</p>';
}
$('#MyDiv').html(lines);
您需要對原始代碼進行兩項更改:
的WebMethod
//Change this line
img.Content = dt.Rows[i]["Content"].ToString();
//Use this instead
img.Content = Convert.ToBase64String(Serialize(dt.Rows[i]["Content"]));
額外方法
public static byte[] Serialize(object obj)
{
var binaryFormatter = new BinaryFormatter();
var ms = new MemoryStream();
binaryFormatter.Serialize(ms, obj);
return ms.ToArray();
}
JavaScript的
//Replace this line
lines += '<p>' + content + '</p>';
//With this one
line += '<p><img src="data:image/jpeg;base64,' + content + '" /></p>';
您可以在Web.config
上設置MaxJsonLength屬性:
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
</configuration>
您可以返回圖像的base64編碼的字符串表示形式。
在輸出圖像的位置,您將擁有:
<img src="data:image/jpeg;base64, <!-- base64 string here -->" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.