简体   繁体   中英

Loading an image from db in C#/asp.net

So I've re-worked the code to work differently now. But my return still seems bugged, or is it not converting the file right?

C# the method which is called on page load.

        private void LoadDisplayPhoto()
    {
        var query = (from q in CurrentContext.DisplayPhotos
                     where q.UserID == CurrentUser.UserId
                     select q.Name).FirstOrDefault();
        if (query != null)
        {
            img_adm.ImageUrl = ("~/HandlerFiles/Display.ashx?ImageID=" + CurrentUser.UserId);
        }
        else
        {
            img_adm.ImageUrl = ("~/Content/img/NoProfilePic.jpg");
        }
    }

The handle file

    public void ProcessRequest (HttpContext context)
{
    byte[] buffer = null;
    string querySqlStr = "";
    //SQL commands.
    if (context.Request.QueryString["ImageID"] != null)
    {
        querySqlStr="select * from DisplayPhotos where PhotoId="+context.Request.QueryString["ImageID"];
    }
    else
    {
        querySqlStr="select * from DisplayPhotos";
    }
    //SQL
    SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["WebTest"].ToString());
    SqlCommand command = new SqlCommand(querySqlStr, connection);
    SqlDataReader reader = null;
    try
    {
        connection.Open();
        reader = command.ExecuteReader();
        while (reader.Read())
        {
            //The ID that was requested.
            int id = Convert.ToInt32(context.Request.QueryString["ImageID"]);
            //Gets extenion format.
            var extension = (from q in CurrentContext.DisplayPhotos
                             where q.UserID == id
                             select q.ContentType).FirstOrDefault();

            string name = reader["Name"].ToString();
            int endIndex = name.LastIndexOf('.');
            buffer = (byte[])reader["Data"];
            context.Response.Clear();
            context.Response.ContentType = "image/" + extension;
            context.Response.BinaryWrite(buffer);
            context.Response.Flush();
            context.Response.Close();
        }
        reader.Close();

    }
    finally
    {
        connection.Close();
    }
}

Name = filename Data = the data which was converted.

My method for uploading the file:

        protected void LinkButton4_Click(object sender, EventArgs e)
    {
        div_editProfile.Visible = true;
        lbl_imgError.Visible = false;
        if (up_ProImg.HasFile)
        {
            int fileLength = up_ProImg.PostedFile.ContentLength;
            string fileName = up_ProImg.PostedFile.FileName;
            string fileType = up_ProImg.PostedFile.ContentType;
            byte[] img = new byte[fileLength];

            var que = from y in CurrentContext.DisplayPhotos
                      where y.Name == fileName
                      select y;
            if (que.Count() > 0)
            {
                lbl_imgError.Visible = true;
                lbl_imgError.Text = "";
            }
            else
            {
                up_ProImg.PostedFile.InputStream.Read(img, 0, fileLength);
                try
                {
                    using (DataContextDataContext udp = new DataContextDataContext())
                    {
                        DisplayPhoto DisP = new DisplayPhoto();
                        DisP.Name = fileName;
                        DisP.ContentType = fileType;
                        DisP.DateLastModified = DateTime.Now;
                        DisP.PhotoId = CurrentUser.UserId;
                        DisP.Data = img;
                        DisP.IsPhoto = true;
                        DisP.IsActive = true;
                        DisP.UserID = CurrentUser.UserId;
                        udp.DisplayPhotos.InsertOnSubmit(DisP);
                        udp.SubmitChanges();
                    }
                }
                finally 
                {
                    var check = from q in CurrentContext.DisplayPhotos
                                where q.Name == fileName
                                select q;

                    if (check.Count() > 0)
                    {
                        lbl_imgError.Visible = true;
                        lbl_imgError.Text = "Image uploaded.";
                    }
                    else
                    {
                        lbl_imgError.Visible = true;
                        lbl_imgError.Text = "Failed to connect to database.";
                    }
                }
            }
        }
        else
        {
            lbl_imgError.Visible = true;
            lbl_imgError.Text = "No image to upload.";
        }
    }

Try to use the ToList method.

 var que = from r in CurrentContext.Photos
          select new
          {
              PhotoId = r.PhotoId,
              Name = r.Name,
              PhotoLink = r.SmallThumbnail
          }.ToList()


<asp:ImageButton ID="imgPhoto" runat="server" Width="80px" Height="80px" OnClick="imgPhoto_Click"  ImageUrl="[PhotoLink]"CssClass="PhotoHandle"/>

Edit [PhotoLink] to the appropriate data attribute

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM