2011-03-31 126 views
1

如何使用C#从SQL数据库检索图像?如何使用C#从SQL数据库检索图像?

+3

Google“Display Blob Image C#” – 2011-03-31 09:47:34

+0

您的方法是什么?为什么它不工作(异常消息,编译器错误...)? – 2011-03-31 09:48:15

+0

继续吧,先试试吧,如果你被困在某个地方,就会复出! – 2011-03-31 09:51:57

回答

0

为什么不尝试使用查询字符串。这里是我的代码,在查询字符串中使用,我从数据库中获取图像,而不必在您的本地文件夹中创建任何想要的图像的instatnce。跳这有助于。

<%@ WebHandler Language="C#" Class="DisplayImg" %> 

using System; 
using System.Web; 
using System.Configuration; 
using System.IO; 
using System.Data; 
using System.Data.SqlClient; 

public class DisplayImg : IHttpHandler 
{ 

    public void ProcessRequest(HttpContext context) 
    { 
     string theID; 
     if (context.Request.QueryString["id"] != null) 
      theID = context.Request.QueryString["id"].ToString(); 
     else 
      throw new ArgumentException("No parameter specified"); 

     context.Response.ContentType = "image/jpeg"; 
     Stream strm = DisplayImage(theID); 
     byte[] buffer = new byte[2048]; 
     int byteSeq = strm.Read(buffer, 0, 2048); 

     while (byteSeq > 0) 
     { 
      context.Response.OutputStream.Write(buffer, 0, byteSeq); 
      byteSeq = strm.Read(buffer, 0, 2048); 
     } 
    } 

    public Stream DisplayImage(string theID) 
    { 
     SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SERVER"].ConnectionString.ToString()); 
     string sql = "SELECT Server_image_icon FROM tbl_ServerMaster WHERE server_Code = @ID"; 
     SqlCommand cmd = new SqlCommand(sql, connection); 
     cmd.CommandType = CommandType.Text; 
     cmd.Parameters.AddWithValue("@ID", theID); 
     connection.Open(); 
     object theImg = cmd.ExecuteScalar(); 
     try 
     { 
      return new MemoryStream((byte[])theImg); 
     } 
     catch 
     { 
      return null; 
     } 
     finally 
     { 
      connection.Close(); 
     } 
    } 

    public bool IsReusable 
    { 
     get 
     { 
      return false; 
     } 
    } 
} 

只需添加一行在CS代码

UploadImg.ImageUrl = “〜/ DisplayImg.ashx ID =?” +代码;

+0

-1不使用'using',不检查空值,并返回方法中的'stream'。 – avishayp 2012-11-16 07:31:07

相关问题