如何使用转发器显示图像

时间:2015-01-03 07:45:43

标签: c# asp.net sql-server

我有一个页面可以将照片上传到我的数据库中。然后当我点击上传时,照片已在数据库中保存为二进制格式:

protected void Button1_Click(object sender, EventArgs e)
{
    Byte[] bytes = null;

    if (FileUpload1.HasFile)
    {
        string filename = FileUpload1.PostedFile.FileName;
        string filePath = Path.GetFileName(filename);

        Stream fs = FileUpload1.PostedFile.InputStream;

        BinaryReader br = new BinaryReader(fs);

        bytes = br.ReadBytes((Int32)fs.Length);
    }

    string cs = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

    SqlConnection con = new SqlConnection(cs);

    SqlCommand cmd = new SqlCommand("INSERT INTO disc_info (disc_name,menu) VALUES('" + TextBox.Text + "','" + bytes + "')", con);

    con.Open();
    cmd.ExecuteNonQuery();

当我尝试检索图像时,它不显示,如何使用转发器显示图像?

数据库:菜单图片

<asp:Image ID="ViewPhotoImage" runat="server" ImageUrl='<%# GetImage(Eval("menu")) %>' Height="190px" Width="180px"/>

public string GetImage(object img)
{
    return "data:image/jpg;base64," + Convert.ToBase64String((byte[]) img);
}

1 个答案:

答案 0 :(得分:1)

我认为您的问题可能在于如何将数据放入数据库。您可能根本没有数据库中的有效图像数据。上传图片时是否会为您运行该代码?当我运行它时,它会在sql命令上出错,因为当你在c#中隐式地将byte []转换为字符串时,你会得到&#34; System.Byte []&#34;而不是数据的字符串表示。你需要convert that byte[] into a binary string。该链接有很多方法可以执行此操作,并且您可以通过以下方式之一使用上传代码(不推荐,请参阅下文):

(编辑,见下面的评论)

Byte[] bytes = null;
string hex = "0";

if (FileUpload1.HasFile)
{
    string filename = FileUpload1.PostedFile.FileName;
    string filePath = Path.GetFileName(filename);

    Stream fs = FileUpload1.PostedFile.InputStream;

    BinaryReader br = new BinaryReader(fs);

    bytes = br.ReadBytes((Int32)fs.Length);
    hex = "0x" + BitConverter.ToString(bytes).Replace("-", "");
}

string cs = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

SqlConnection con = new SqlConnection(cs);

SqlCommand cmd = new SqlCommand("INSERT INTO disc_info (disc_name,menu) VALUES('" + TextBox.Text + "'," + hex + ")", con);

con.Open();
cmd.ExecuteNonQuery();             

您也可能希望将该sql代码移动到if块中,但也许这就是您想要的,只是我想提到它以防万一。

<强>无论其...

如果我没有强烈建议你参数化你的sql语句以避免注入攻击,那将是我的疏忽。但它不仅对安全性更好,而且因为不需要字符串转换,所以更容易使用二进制数据。这是带参数的相关代码:

Byte[] bytes = null;

if (FileUpload1.HasFile)
{
    Stream fs = FileUpload1.PostedFile.InputStream;

    BinaryReader br = new BinaryReader(fs);

    bytes = br.ReadBytes((Int32)fs.Length);
}

string cs = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

SqlConnection con = new SqlConnection(cs);

SqlCommand cmd = new SqlCommand("INSERT INTO disc_info (disc_name,menu) VALUES(@disc, @menu)", con);
cmd.Parameters.AddWithValue("@disc", TextBox.Text);
cmd.Parameters.AddWithValue("@menu", bytes);
con.Open();
cmd.ExecuteNonQuery();   

一旦我这样做,你的其他代码工作正常,我能够在转发器中看到我的测试图像。我希望有所帮助!