如何下载存储在SQL Server数据库中的图像?

时间:2017-07-09 13:25:03

标签: c# sql guid

我正在创建一个Web表单应用程序,允许用户将图像文件上载到文件夹并将其路径存储在数据库中。我想使用一个链接按钮,它将从数据库中下载文件

这是我上传的代码

protected void btnSubmit_Click(object sender, EventArgs e)
{
    con.Open();

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandText = "UPDATE Orders SET PaymentImage = @Image, PaymentStatus = @PaymentStatus WHERE OrderNo = @OrderNo AND PaymentStatus = 'Pending'; ";

    string fileExt = Path.GetExtension(fuImage.FileName);
    string id = Guid.NewGuid().ToString();

    cmd.Parameters.AddWithValue("@OrderNo", Request.QueryString["ID"].ToString());
    cmd.Parameters.AddWithValue("@Image", id + fileExt);
    cmd.Parameters.AddWithValue("@PaymentStatus", "Payment Sent");

    fuImage.SaveAs(Server.MapPath("~/img/payments/" + id + fileExt));

    cmd.ExecuteNonQuery();
    con.Close();

    Response.Redirect("Default.aspx");
}

更新2:这是我尝试过的下载按钮

protected void btnDownload_Click(object sender, EventArgs e)
{
    String orderNo = Request.QueryString["ID"].ToString();
    con.Open();
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandText = "SELECT OrderNo, PaymentImage FROM Orders WHERE OrderNo=@OrderNo";
    cmd.Parameters.AddWithValue("@OrderNo", Request.QueryString["ID"].ToString());
    SqlDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        Guid id = (Guid)(dr["PaymentImage"]);          
        Response.TransmitFile(Server.MapPath("~/img/payments/" + id + ".jpg"));
    }
    con.Close();
}

现在我收到此错误“指定的强制转换无效”。

0 个答案:

没有答案