Click here to Skip to main content
Licence Apache
First Posted 18 Apr 2004
Views 168,135
Bookmarked 60 times

Storing Images in MySQL using ASP.NET

By | 18 Apr 2004 | Article
This article describes on how to set up a MySQL database to store images with ASP.NET and display it back to the browser.
 
Part of The SQL Zone sponsored by
See Also

Introduction

This article describes how to upload images to a web server using ASP.NET. All the data is stored in a MySQL database. This article is targeted towards a little more intermediate programmer who has some understanding of ASP.NET with C#, SQL and relational databases. First section describes how to set up the database and second part describes how to code uploading the files and how to view them back as a gallery. Code has been tested with JPEG and GIF files.

Setting Up the Database

The database that I have used is MySQL. Information on how to obtain and install MySQL can be obtained from here. To make the process of creation and interacting with the database, I used MySQL control center. This allows a visual way for creating and interacting with a MySQL database.

MySQL comes with a default database called test. And I will be using this database.

MySql Control Center

The next thing is to create a table called file with the following columns.

  • ID – Select it to be a timestamp to create it as the primary key of the table.
  • Extension – Select it as varchar.
  • Data – Select it as longblob.

MySql Control Center Table View

To connect to the MySQL database, MySQL ODBC driver has to be downloaded. The version of MySQL ODBC driver is 3.51 that I have used for this article. All the code to interact with database is placed in a DataAccess class.

public class DataAccess
{
    private string _strConn = 
        @"Driver=   {MySQLODBC 3.51 Driver};SERVER=localhost;DATABASE=test;"; 

    private OdbcConnection _objConn;

    public DataAccess()
    {
        this._objConn = new OdbcConnection(this._strConn);  
    }
    // This function adds the Images to database

    public string addImage(byte [] buffer,string extension)
    {
        string strSql = "SELECT * FROM File";
        DataSet ds = new DataSet("Image");
        OdbcDataAdapter tempAP = new OdbcDataAdapter(strSql,this._objConn);
        OdbcCommandBuilder objCommand = new OdbcCommandBuilder(tempAP);
        tempAP.Fill(ds,"Table");

        try
        {
            this._objConn.Open();
            DataRow objNewRow = ds.Tables["Table"].NewRow();
            objNewRow["Extension"] = extension;
            objNewRow["Data"] = buffer;
            ds.Tables["Table"].Rows.Add(objNewRow);
            // trying to update the table to add the image
            tempAP.Update(ds,"Table"); 
        }
        catch(Exception e){return e.Message;}
        finally{this._objConn.Close();}
        return null;
    }
    // This function to get the image data from the database

    public byte [] getImage(int imageNumber)
    {
        string strSql = "SELECT * FROM File";
        DataSet ds = new DataSet("Image");
        OdbcDataAdapter tempAP = new OdbcDataAdapter(strSql,this._objConn);
        OdbcCommandBuilder objCommand = new OdbcCommandBuilder(tempAP);
        tempAP.Fill(ds,"Table");

        try
        {
            this._objConn.Open();
            byte [] buffer = (byte [])ds.Tables["Table"].Rows[imageNumber]["Data"];
            return buffer;
        }
        catch{this._objConn.Close();return null;}
        finally{this._objConn.Close();}            
    }
    // Get the image count

    public int getCount()
    {
        string strSql = "SELECT COUNT(Data) FROM File";
        DataSet ds = new DataSet("Image");
        OdbcDataAdapter tempAP = new OdbcDataAdapter(strSql,this._objConn);
        OdbcCommandBuilder objCommand = new OdbcCommandBuilder(tempAP);
        tempAP.Fill(ds,"Table");

        try>
        {
            this._objConn.Open();
            int count = (int)ds.Tables["Table"].Rows[0][0];
            return count;
        }
        catch{this._objConn.Close();return 0;}
        finally{this._objConn.Close();}
    }

}

Getting the User Uploaded files

To upload the files to the web server, a very simple ASP.NET web form is used, which is composed of a file field and a submit button. The Web form file in the project is Upload.aspx and the code is place in Upload.aspx.cs. The file is obtained and put in the database in the Page_Load function. Now the code takes a look into the Request.Files collection. As the interface allows to upload only one file, therefore, we check it if there is a file pending on IIS. The code checks for the mime type of the file if it is an image it accepts, otherwise it just displays a message that mime type is not supported. If the file is an image, data is read in bytes and inserted into the MySQL database using the DataAccess class object.

private void Page_Load(object sender, System.EventArgs e)
{
    //Checking if there are any files avaiable on IIS.
    if(Request.Files.Count != 0)
    {               
        HttpPostedFile httpFile = Request.Files[0];
        // Checking for extension
        string extension = this.getFileExtension(httpFile.ContentType);
        if(extension == null )
        {
            Response.Write("Mime type not Supported");
            return;
        }
        System.IO.BufferedStream bf = new BufferedStream(httpFile.InputStream);
        byte[] buffer = new byte<bf.Length>;  
        bf.Read(buffer,0,buffer.Length);               
        // Creating the database object
        DataAccess data = new DataAccess();
        // Adding files to the database.
        data.addImage(buffer,extension);
        Response.Write("Image Added!");
 
    }
}

MySql Control Center Table View

Displaying Upload File

Now, to display the uploaded files for the user, another Web form is setup in a file called View.aspx. Getting the image data is done by another file called show.aspx.

private void Page_Load(object sender, System.EventArgs e)
{
    // Put user code to initialize the page here
    Data.DataAccess data = new Data.DataAccess();
    int imagenumber = 0;
    try
    {
        imagenumber = int.Parse(Request.QueryString["image"]);
    }
    catch(System.ArgumentNullException ee)
    {
        imagenumber = 0;
    }

    byte []  buffer = data.getImage(imagenumber);
    System.IO.MemoryStream stream1 = new System.IO.MemoryStream(buffer,true);   
    stream1.Write(buffer,0,buffer.Length);
    Bitmap m_bitmap = (Bitmap) Bitmap.FromStream(stream1,true);
    Response.ContentType = "Image/jpeg";
    m_bitmap.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);
}

View.aspx allows the user to go to the next file by clicking next link.

View.aspx

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0

About the Author

Fahad Azeem

Web Developer

United States United States

Member

My name is Fahad Azeem. I am interested in distributed software development. Currently I am working for a software consulting company in Chicago which developes software in .NET platform.
 
My Blog: http://fahadaz.blogspot.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralFull code needed Pinmemberlitiso7:43 16 Sep '09  
Generalwhere to learn Pinmembernotexpert11:11 14 Sep '09  
GeneralRe: where to learn PinmemberFahad Azeem12:06 14 Sep '09  
GeneralRe: where to learn Pinmembernotexpert12:49 14 Sep '09  
Generaltype or namespace name 'Bitmap' could not be found Pinmembernotexpert9:38 14 Sep '09  
GeneralRe: type or namespace name 'Bitmap' could not be found PinmemberFahad Azeem9:40 14 Sep '09  
GeneralRe: type or namespace name 'Bitmap' could not be found Pinmembernotexpert9:57 14 Sep '09  
QuestionHELP: Buffer cannot be null. Parameter name: buffer Pinmemberjack package22:49 14 Jul '09  
Questionhow to slove Pinmemberglitto1:12 8 Oct '07  
QuestionHow overcome below error Pinmemberbochkari20:30 19 Aug '07  
GeneralParameter is not Valid Pinmemberderektaprell15:48 10 Apr '07  
GeneralRe: Parameter is not Valid PinmemberFahad Azeem5:30 12 Apr '07  
GeneralRe: Parameter is not Valid Pinmembermadis825:48 21 May '10  
GeneralUploading iamges to mysql database Pinmemberv.venkannababu0:49 1 Jun '06  
GeneralWhere do you referred for this Topic Pinmembervivekthangaswamy19:37 27 Nov '05  
GeneralRe: Where do you referred for this Topic PinmemberFahad Azeem3:48 28 Nov '05  
GeneralHTTP 405 Pinmemberfavila16:46 9 Jun '05  
GeneralRe: HTTP 405 PinmemberFahad Azeem7:23 12 Jun '05  
GeneralRe: HTTP 405 Pinmemberfavila6:39 13 Jun '05  
GeneralAuto-increment fields in database Pinmembercyber0ne5:00 14 Feb '05  
GeneralRe: Auto-increment fields in database Pinmemberdaddion7:23 16 Feb '05  
The MySQL engine should handle this. If you created the table with the auto-increment constraint then inserting data will cause MySQL to increment the row id. I used this code and it incremented just as if I had used "INSERT INTO..." You may want to check your table again.
GeneralRe: Auto-increment fields in database Pinmembercyber0ne9:33 16 Feb '05  
GeneralRe: Auto-increment fields in database Pinmemberdaddion10:40 17 Feb '05  
GeneralRe: Auto-increment fields in database Pinmemberdaddion3:22 21 Feb '05  
GeneralRe: Auto-increment fields in database Pinmembercyber0ne3:13 24 Feb '05  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120528.1 | Last Updated 19 Apr 2004
Article Copyright 2004 by Fahad Azeem
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid