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

.NET Image Uploading

Rate me:
Please Sign up or sign in to vote.
4.65/5 (59 votes)
12 Mar 20022 min read 811.5K   11.2K   175   112
Uploading images in .NET and thumbnailing, resizing, etc.

Uploading images via .NET

Previously, adding the ability to upload images via ASP (with sizing, thumbnail features, etc.) would have required the use of an external component. With the advent of .NET, the ability to handle images can be done easily and freely through the use of the Bitmap and Image classes.

In this tutorial, we will be going through the steps of creating a simple web form in which you can upload an image file, and the form will verify whether it’s a JPEG file, whether there are duplicate files already (and rename your uploaded file if necessary), and create a thumbnail of the file uploaded.

This tutorial already assumes a basic knowledge of .NET Web Forms and C#.

By the way, some credit goes to Konstantin Vasserman for his code on uploading. If you need to upload the image into a DB, then look at his article.

  1. Create a new web application project.

  2. Open up the web form.

  3. Add a File field from the HTML tab onto your form, and convert it into a server control. In this example, the file field will be named filUpload.
    (To convert any HTML tag into a server control, right click on it and select Run As Server Control.)

  4. Switch to HTML view and add/alter the enctype attribute of the form tag to multipart/form-data.
    Example: enctype="multipart/form-data"

  5. Add a Web Form Button onto the form, and name it btnUpload.

  6. Add a folder called /images to the web application.

  7. Add a Web Form Image onto the form, and name it imgPicture. Adjust the width to 160 and height to 120.

  8. Add a Label called lblOutput. This will return any errors if the upload happens to fail.

  9. In the btnUpload Click event, add the following code.
    (If you want to analyze the code in detail below, it's better to copy and paste into the VS.NET IDE since some of the lines are long.)
    C#
    private void btnUpload_Click(object sender, System.EventArgs e)
    {
        // Initialize variables
        string sSavePath;
        string sThumbExtension;
        int intThumbWidth;
        int intThumbHeight;
    
        // Set constant values
        sSavePath = "images/";
        sThumbExtension = "_thumb";
        intThumbWidth = 160;
        intThumbHeight = 120;
    
        // If file field isn’t empty
        if (filUpload.PostedFile != null)
        {
            // Check file size (mustn’t be 0)
            HttpPostedFile myFile = filUpload.PostedFile;
            int nFileLen = myFile.ContentLength;
            if (nFileLen == 0)
            {
                lblOutput.Text = "No file was uploaded.";
                return;
            }
    
            // Check file extension (must be JPG)
            if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
            {
                lblOutput.Text = "The file must have an extension of JPG";
                return;
            }
    
            // Read file into a data stream
            byte[] myData = new Byte[nFileLen];
            myFile.InputStream.Read(myData,0,nFileLen);
    
            // Make sure a duplicate file doesn’t exist.  If it does, keep on appending an 
            // incremental numeric until it is unique
            string sFilename = System.IO.Path.GetFileName(myFile.FileName);
            int file_append = 0;
            while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
            {
                file_append++;
                sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
                                 + file_append.ToString() + ".jpg";
            }
    
            // Save the stream to disk
            System.IO.FileStream newFile
                    = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename), 
                                               System.IO.FileMode.Create);
            newFile.Write(myData,0, myData.Length);
            newFile.Close();
    
            // Check whether the file is really a JPEG by opening it
            System.Drawing.Image.GetThumbnailImageAbort myCallBack = 
                           new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
            Bitmap myBitmap;
            try
            {
                myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename));
    
                // If jpg file is a jpeg, create a thumbnail filename that is unique.
                file_append = 0;
                string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
                                                         + sThumbExtension + ".jpg";
                while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
                {
                    file_append++;
                    sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + 
                                   file_append.ToString() + sThumbExtension + ".jpg";
                }
    
                // Save thumbnail and output it onto the webpage
                System.Drawing.Image myThumbnail
                        = myBitmap.GetThumbnailImage(intThumbWidth, 
                                                     intThumbHeight, myCallBack, IntPtr.Zero);
                myThumbnail.Save (Server.MapPath(sSavePath + sThumbFile));
                imgPicture.ImageUrl = sSavePath + sThumbFile;
    
                // Displaying success information
                lblOutput.Text = "File uploaded successfully!";
    
                // Destroy objects
                myThumbnail.Dispose();
                myBitmap.Dispose();
            }
            catch (ArgumentException errArgument)
            {
                // The file wasn't a valid jpg file
                lblOutput.Text = "The file wasn't a valid jpg file.";
                System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
            }
        }
    }
    
    public bool ThumbnailCallback()
    {
        return false;
    }        
  10. Run the webpage, and test with JPG files and other files to test the error-checking mechanism.

  11. If you have any problems/suggestions, please leave a message below. :-)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: VB.NET complete Pin
ThaSaint24-May-05 1:06
ThaSaint24-May-05 1:06 
GeneralVB.NET version (some not all) Pin
Anonymous10-Apr-04 4:06
Anonymous10-Apr-04 4:06 
QuestionPNG? Pin
Reinholdt29-Mar-04 22:09
Reinholdt29-Mar-04 22:09 
QuestionFile not a valid jpg file?? Pin
Reinholdt29-Mar-04 21:56
Reinholdt29-Mar-04 21:56 
AnswerRe: File not a valid jpg file?? Pin
Charles T II6-Dec-04 23:37
Charles T II6-Dec-04 23:37 
QuestionGoing straight to Bitmap? Pin
ARatcliffe19-Jan-04 1:58
ARatcliffe19-Jan-04 1:58 
GeneralUploaded File Retrieval Pin
learningProcess3-Jan-04 4:06
learningProcess3-Jan-04 4:06 
GeneralRe: Uploaded File Retrieval Pin
sandeep_gwalior7-Oct-05 7:09
sandeep_gwalior7-Oct-05 7:09 
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.



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.


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!");

}
}


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.




hello...This is sandeep vyas, software developer in pune and i wanna join code project
GeneralUploading images using Web Matrix Pin
BaiLong6-Oct-03 18:16
BaiLong6-Oct-03 18:16 
GeneralRe: Uploading images using Web Matrix Pin
ARatcliffe19-Jan-04 2:04
ARatcliffe19-Jan-04 2:04 
Questionhow to save only thumbnail immage not both Pin
Ganesh M16-Sep-03 21:29
Ganesh M16-Sep-03 21:29 
QuestionShouldn't you use ContentType? Pin
cazzz27-Aug-03 5:19
cazzz27-Aug-03 5:19 
Questionwhy don't use htmlInputFiel to upload file ? Pin
bibotaphack16-Jul-03 16:40
bibotaphack16-Jul-03 16:40 
GeneralUnauthorizedAccessException Pin
yarix26-Apr-03 8:01
yarix26-Apr-03 8:01 
GeneralRe: UnauthorizedAccessException Pin
n4mation2-Apr-04 22:41
n4mation2-Apr-04 22:41 
GeneralRe: UnauthorizedAccessException Pin
Maracuja19-May-04 21:58
Maracuja19-May-04 21:58 
GeneralRe: UnauthorizedAccessException Pin
Anonymous24-Jun-04 4:33
Anonymous24-Jun-04 4:33 
GeneralRe: UnauthorizedAccessException Pin
Anonymous17-Jul-04 1:32
Anonymous17-Jul-04 1:32 
GeneralVery Cool Pin
DFU236-Mar-03 4:25
DFU236-Mar-03 4:25 
GeneralThumbnailCallback Pin
topicomha17-Feb-03 11:04
topicomha17-Feb-03 11:04 
GeneralRe: ThumbnailCallback Pin
Anonymous7-Oct-03 8:37
Anonymous7-Oct-03 8:37 
Generalnot decompressing the jpeg Pin
tomthumb11122-Nov-02 9:23
susstomthumb11122-Nov-02 9:23 
Generallooking for help Pin
Anonymous22-Jul-02 21:19
Anonymous22-Jul-02 21:19 
GeneralA little bit complex... Pin
Kupfernagel@ludwig-hoehne.de12-Jul-02 0:36
sussKupfernagel@ludwig-hoehne.de12-Jul-02 0:36 
Generalerror in parsing with webmatrix Pin
Syd10-Jul-02 23:09
Syd10-Jul-02 23:09 

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.