Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# c使用处理程序显示数据库中的特定图像_C#_Sql_Asp.net_Image - Fatal编程技术网

C# c使用处理程序显示数据库中的特定图像

C# c使用处理程序显示数据库中的特定图像,c#,sql,asp.net,image,C#,Sql,Asp.net,Image,我有一个数据库,有3个表,其中一个表上载了用户的图片,每个表都有一个配置文件页。我曾在登录和搜索中使用gridview显示图片,但不太美观,因此我决定采用asp:image方法: 我现在不能做的是显示登录用户的图像或搜索后显示的用户个人资料 那么如果我找到一种方法将id传递给处理程序?还是 谢谢你的帮助 Default.aspx.cs在Imageupload和ImagebindGrid中发生。我已经绕过了gridview代码,所以我可以尝试用另一种方式显示它 using System; usi

我有一个数据库,有3个表,其中一个表上载了用户的图片,每个表都有一个配置文件页。我曾在登录和搜索中使用gridview显示图片,但不太美观,因此我决定采用asp:image方法:

我现在不能做的是显示登录用户的图像或搜索后显示的用户个人资料

那么如果我找到一种方法将id传递给处理程序?还是

谢谢你的帮助

Default.aspx.cs在Imageupload和ImagebindGrid中发生。我已经绕过了gridview代码,所以我可以尝试用另一种方式显示它

 using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Security.Principal;
using System.Data.Common;



namespace DisplayingImages
{
public partial class Default : System.Web.UI.Page
{

    public string query, constr, query1, query2, query3;
    public SqlConnection con, conn;
    public void connection()
    {
        constr = ConfigurationManager.ConnectionStrings["Myconnection"].ToString();
        con = new SqlConnection(constr);
        con.Open();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Visible = false;
        if (!IsPostBack)
        {


            EM = (string)(Session["Email_Account"]); 
            lblemail.Text = EM;
            SN = Convert.ToString(Session["Surname"]);
            lblname.Text = SN; 
            PS = (string)(Session["Password"]);
            PID = (int)(Session["id"]);
            HttpContext context = HttpContext.Current;
            context.Session["Email_Account"] = EM;
            EM = (string)(context.Session["Email_Account"]);
            if (PID == null)
            {
                Response.Redirect("Login.aspx");
            }
            imagebindGrid();
            PostSelection();


        }
    }

    private void InitializeComponent()
    {
        throw new NotImplementedException();
    }


    protected void upload(object sender, EventArgs e) // button για το upload της φωτο. Καλειται η κλαση Imageupload()
    {

        Imageupload();
    }
    /* Κλασση για upload εικονας . Ελεγχος και περασμα εικονας */
    private void Imageupload()
    {
        if (FileUpload1.HasFile)
        {
            PID = (int)(Session["id"]);
            if (PID != null)
            {
                int imagefilelenth = FileUpload1.PostedFile.ContentLength;
                byte[] imgarray = new byte[imagefilelenth];
                HttpPostedFile image = FileUpload1.PostedFile;
                image.InputStream.Read(imgarray, 0, imagefilelenth);
                connection();
                query = "Insert into  ImageToDB (user_id,ImageName,Image) values (@user_id,@Name,@Image)";
                SqlCommand com = new SqlCommand(query, con);
                com.Parameters.AddWithValue("@Name", SqlDbType.VarChar).Value = TextBox1.Text;
                com.Parameters.AddWithValue("@Image", SqlDbType.Image).Value = imgarray;
                com.Parameters.AddWithValue("@user_id", PID);
                com.ExecuteNonQuery();
                Label1.Visible = true;
                Label1.Text = "Image Is Uploaded successfully";
                imagebindGrid();

            }
        }
    }
    /* Gridview για εικονες */
    public void imagebindGrid()
    {
        connection();
        query = "Select id,ImageName,Image from ImageToDB where user_id= " + PID;
        SqlCommand com = new SqlCommand(query, con);
        SqlDataReader dr = com.ExecuteReader();
        //Image.ImageUrl = "/Handler.ashx?id_Image=" + PID.ToString();      


        //Gridview1.DataSource = dr;
        //Gridview1.DataBind();


    }
    /*Logout Button */
    protected void Button1_Click(object sender, EventArgs e)
    {

        System.Web.Security.FormsAuthentication.SignOut();
        Session.Clear();
        Session.RemoveAll();
        Session.Abandon();
        Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetNoStore();
        HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        HttpContext.Current.Response.AddHeader("Pragma", "no-cache");
        HttpContext.Current.Response.AddHeader("Expires", "0");
        FormsAuthentication.SignOut();
        HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);
        Response.Redirect("~/Logout.aspx");
    }
    /* Κλασση για το Post */
    private void Txt()
    {
        try
        {
            PID = (int)(Session["id"]);
            if (PID != null)
            {
                connection();
                query1 = "Insert into  Posttext (user_id,Posttext) values (@user_id,@Your_Post)";
                SqlCommand com2 = new SqlCommand(query1, con);
                com2.Parameters.AddWithValue("@Your_Post", SqlDbType.VarChar).Value = PostBox.Text;
                com2.Parameters.AddWithValue("@user_id", PID);
                com2.ExecuteNonQuery();
                lbluser.Text = PostBox.Text;
                PostSelection();
            }

        }



        catch (Exception ex)
        {
            //con.Close();
        }

    }
    /* Κανει select τα κειμενα και τα ανεβαζει απο την βαση στο grid */
    public void PostSelection()
    {
        connection();

        query2 = "Select Posttext from Posttext where user_id= " + PID;
        SqlCommand com1 = new SqlCommand(query2, con);
        SqlDataReader Read = com1.ExecuteReader();
        grdemployee7.DataSource = Read;
        grdemployee7.DataBind();
        Read.Close();

    }
    /* Καλειται η Txt() για να γινει το Post */
    protected void Button2_Click(object sender, EventArgs e)
    {
        Txt();
    }

    public string USER_PID { get; set; }
    public DateTime _myid { get; set; }

    /* --------------------Κουμπι για search PROFILE -----------------------------------*/
    public void Button3_Click1(object sender, EventArgs e)
    {
                Response.Redirect("~/WebForm7.aspx");
    }

    public string SN { get; set; }
    public string PS { get; set; }
    public string EM { get; set; }
    public int PID { get; set; }

    protected void PostBox_TextChanged(object sender, EventArgs e)
    {

    }
}
}
这是我的经纪人

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace DisplayingImages
{
/// <summary>
/// Summary description for Handler1
/// this application is created by vithal wadje for C# corner
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class Handler1 : IHttpHandler
{
    //createting the object of Default.aspx class page to 
    //call connection and use strings variable
    Default cls = new Default();

    public void ProcessRequest(HttpContext context)
    {
        //storing the querystring value that comes from Defaul.aspx page

        string displayimgid = context.Request.QueryString["id_Image"].ToString();
        cls.connection();
        //retriving the images on the basis of id of uploaded 
        //images,by using the querysting valaues which comes from Defaut.aspx page
        cls.query = "select Image from ImageToDB where id=" + displayimgid;
        SqlCommand com = new SqlCommand(cls.query, cls.con);
        SqlDataReader dr = com.ExecuteReader();
        dr.Read();
        context.Response.BinaryWrite((Byte[])dr[0]);
        context.Response.End();

    }

    public bool IsReusable
    {
        get
        {
            return true;
        }
    }
}
}
这是我传递身份证的方式

<asp:Image ID="Image" runat="server" ImageUrl='<%# "Handler1.ashx?id_Image="+ Eval("id") %>' "/>
代码可能看起来有点混乱,但我尝试了一些事情却没有成功

再次感谢

您需要为此设置contenttype。否则它将是二进制的。用这个

context.Response.ContentType=image/png

这取决于您正在编写的图像类型。基于此,请使用image/jpg等

除此之外,我可以在您的代码中看到,您已经使用imagebindGrid通过查询SQL将图像绑定到网格,但在绑定到网格之前没有使用dr.Read,这将不会打开行集,因此没有数据绑定,也看不到新图像。所以新代码如下所示

 SqlDataReader dr = com.ExecuteReader();
 dr.Read();
 Gridview1.DataSource = dr;
 Gridview1.DataBind();

如果您可以在有Gridview1的地方显示aspx代码,这将更有助于您,以防您在更改后遇到问题。

当您直接在浏览器中执行该处理程序时会发生什么情况?请注意,您的代码中存在SQL注入漏洞。永远不要将用户输入视为可执行的SQL代码。在某些查询中,您已经使用参数来防止这种情况。为什么不在所有查询中使用它们?更重要的是。。。该代码在何处/如何失败?URL呈现是否正确?它是否正确地请求处理程序?处理程序是否使用图像数据进行响应?问题到底出在哪里?是的,我将修复所有这些SQL不安全性,感谢您的提及!:代码只是没有显示图像,当我把静态id_image=1放在.aspx时,它显示了表的第一张图片,但是对于每个用户。。。现在,我正在尝试根据用户id改变图片的动态方法!是的,但这不是实际的图像文件,您正在拦截它,因此必须在拦截器中设置内容类型。若要验证这一点,请使用加载页面,请参阅。图像的内容类型将在网络控制台中设置为图像。因为浏览器需要将二进制数据解释为图像,否则这只是对浏览器的文本响应,您可以看到浏览器控制台,它会说错误,请参阅一些有用的帖子-,这可能与OP的问题无关,但这仍然是我试图解释的一个很好的例子。你可能是对的。将删除评论。让OP检查一下。我把它改为img src=并在代码中得到了上下文响应,但什么都没有,真正的问题是id解析到id_图像html,因为当我使用静态数字时,比如我得到的图片很好@frcake,我可以在您的代码中看到,您已经使用imagebindGrid通过查询SQL将图像绑定到网格,但在绑定到网格之前您还没有使用dr.Read,这将不会打开行集,因此没有绑定数据,也看不到新图像。