Click here to Skip to main content
15,891,777 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hi Guys...
In my webpage how can i store the images in database as well as retrieve from the database.
Posted

Retrieve is easy: A generic Image-From-DB class for ASP.NET[^]

Insert is harder:
1) Add a Upload control to your page.
2) Handle the Click event, and call this:
C#
/// <summary>
/// Save an upload into the database.
/// </summary>
/// <param name="fl">Control containing the download.</param>
/// <returns>Status as a string</returns>
private string SaveUpload(FileUpload fl)
    {
    if (fl.HasFile)
        {
        try
            {
            int version = 0;
            string filename = Path.GetFileName(fl.FileName);
            byte[] filedata = fl.FileBytes;
            string strCon = ConnectionStrings.Download;
            using (SqlConnection con = new SqlConnection(strCon))
                {
                con.Open();
                // Check version - if the file exists in the DB already, then increase version number.
                using (SqlCommand ver = new SqlCommand("SELECT MAX(version) FROM dlContent WHERE fileName=@FN", con))
                    {
                    ver.Parameters.AddWithValue("@FN", filename);
                    object o = ver.ExecuteScalar();
                    if (o != null && o != System.DBNull.Value)
                        {
                        // Exists already.
                        version = (int) o + 1;
                        }
                    }
                // Stick file into database.
                using (SqlCommand ins = new SqlCommand("INSERT INTO dlContent (iD, fileName, description, dataContent, version, uploadedOn) " +
                                                       "VALUES (@ID, @FN, @DS, @DT, @VS, @UD)", con))
                    {
                    ins.Parameters.AddWithValue("@ID", Guid.NewGuid());
                    ins.Parameters.AddWithValue("@FN", filename);
                    ins.Parameters.AddWithValue("@DS", "");
                    ins.Parameters.AddWithValue("@DT", filedata);
                    ins.Parameters.AddWithValue("@VS", version);
                    ins.Parameters.AddWithValue("@UD", DateTime.Now);
                    ins.ExecuteNonQuery();
                    }
                }
            return string.Format("{0} uploaded, version = {1}", filename, version);
            }
        catch (Exception ex)
            {
            return "The file could not be uploaded. The following error occured: " + ex.Message;
            }
        }
    return "Please select a file.";
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900