Click here to Skip to main content
15,881,281 members
Articles / Web Development / ASP.NET
Article

Storing Images in MySQL using ASP.NET

Rate me:
Please Sign up or sign in to vote.
3.10/5 (8 votes)
18 Apr 2004Apache2 min read 268.9K   3.8K   61   48
This article describes on how to set up a MySQL database to store images with ASP.NET and display it back to the browser.

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.

C#
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.

C#
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.

C#
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


Written By
Web Developer
United States United States
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

Comments and Discussions

 
GeneralVery interesting but explain please! Pin
dleec452-May-04 12:51
dleec452-May-04 12:51 
GeneralRe: Very interesting but explain please! Pin
Fahad Azeem2-May-04 16:28
Fahad Azeem2-May-04 16:28 
GeneralPerformance Pin
Anonymous29-Apr-04 4:39
Anonymous29-Apr-04 4:39 
GeneralRe: Performance Pin
Fahad Azeem29-Apr-04 5:01
Fahad Azeem29-Apr-04 5:01 
GeneralRe: Performance Pin
christopher crowe6-Dec-04 7:37
christopher crowe6-Dec-04 7:37 
GeneralRe: Performance Pin
Fahad Azeem6-Dec-04 7:43
Fahad Azeem6-Dec-04 7:43 
GeneralRe: Performance Pin
daddion8-Feb-05 4:14
daddion8-Feb-05 4:14 
GeneralRe: Performance Pin
christopher crowe8-Feb-05 11:38
christopher crowe8-Feb-05 11:38 
Yes. This is something a little different.

You are correct in thinking that you would want to select a smaller set of records if you were retrieving pictures. However, you would not want to select any when uploading.

It is a constraint of using the DataSet object. The DataSet always needs a schema to work correctly. One way to load the schema is to select some records from the table. This action implicity reads the schema into the DataSet object.

With a majority of tables, this activity does not incur an appreciable cost, however, when dealing with BLOBs, it can be a huge issue (since they are traditionally huge). If you were only reading the schema to upload (not to view), there would be no point in loading any records at all.

So providing the "impossible" WHERE clause insures that the DataSet will implicitly read in the schema of the table to which you wish to upload, without being hit with any overhead for data transfer (which you will never view anyway).

I hope that answers your question.

CJC
GeneralRe: Performance Pin
daddion8-Feb-05 15:14
daddion8-Feb-05 15:14 
GeneralRe: Performance Pin
Zachary Yates19-Feb-05 5:50
Zachary Yates19-Feb-05 5:50 
GeneralRe: Performance Pin
apexi_2-Aug-05 0:05
apexi_2-Aug-05 0:05 
GeneralGood One! Pin
Mubi | www.mrmubi.com22-Apr-04 18:19
professionalMubi | www.mrmubi.com22-Apr-04 18:19 
GeneralRe: Good One! Pin
Fahad Azeem25-Apr-04 6:50
Fahad Azeem25-Apr-04 6:50 
GeneralNice article Pin
Gevik Babakhani20-Apr-04 21:44
Gevik Babakhani20-Apr-04 21:44 
GeneralImages do not display + Formatting Pin
Okeno Palmer19-Apr-04 17:52
Okeno Palmer19-Apr-04 17:52 

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

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