如何在asp.net中从数据库中检索和显示图像

时间:2013-07-26 12:50:44

标签: c# asp.net

我将从数据库中显示图像作为用户输入图像ID。我必须在它下方的图片框中显示它。

我使用此代码将base64string转换为image

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["ImageID"] != null)
        {
            string ImgData = Request.QueryString["ImageID"].ToString();
            Byte[] bytes = Convert.FromBase64String(ImgData);
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "image/jpg";
            Response.AddHeader("content-disposition", "attachment;");
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }
    }
}

我的主要网页源代码是

protected void Button1_Click(object sender, EventArgs e)
    {
        NpgsqlCommand cmd = null;
        string selPhoto = @"select * from photodetails where photoid=@photoid";
        System.Drawing.Image newImage;
        string tempfilename=@"C:\Users\Public\temp_image";
        try
        {
            cmd = new NpgsqlCommand(selPhoto, con);

            cmd.Parameters.Add("@photoid",Convert.ToInt16(txtpid.Text));
            if (con.State == ConnectionState.Open)
                con.Close();
            con.Open();

            NpgsqlDataReader drphoto = cmd.ExecuteReader();
            while (drphoto.Read())
            {
                //System.IO.Stream fs = FileUpload1.PostedFile.InputStream;
                //System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
                Byte[] bytes = (byte[])drphoto["photo_bytearr"]; //br.ReadBytes((Int32)fs.Length);
                string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
                img1.ImageUrl = @"http://localhost:29450/SampleWeb/showimg.aspx?ImageData=" + Convert.ToBase64String(bytes);                
            }

        }
        catch (Exception ex)
        {

        }
    }

但是它仍然没有显示图像?

1 个答案:

答案 0 :(得分:2)

以下行无效。

img1.ImageUrl = @"http://localhost:29450/SampleWeb/showimg.aspx?ImageData=" + Convert.ToBase64String(bytes);

相反传递图像的id,并查看,与尝试通过url传递binarydata。

img1.ImageUrl = @"http://localhost:29450/SampleWeb/showimg.aspx?ImageId=" + imageId; 

注意:Internet Explorer只允许在您的网址中包含2,048个字符。