Click here to Skip to main content
11,647,170 members (69,768 online)
Click here to Skip to main content

.NET Image Uploading

, 12 Mar 2002 604.2K 10.4K 173
Rate this:
Please Sign up or sign in to vote.
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.)
    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. Smile | :)

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

Share

About the Author

Chris Khoo
Australia Australia
No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralVoted 4 Pin
Sivaraman Dhamodharan16-May-15 5:59
memberSivaraman Dhamodharan16-May-15 5:59 
QuestionImage upload in asp.net Pin
Md. Rashedul Hasan12-Nov-12 0:04
memberMd. Rashedul Hasan12-Nov-12 0:04 
QuestionImage upload Pin
shanid3602-Aug-12 20:34
membershanid3602-Aug-12 20:34 
GeneralMy vote of 5 Pin
tanweer akhtar29-Jun-12 2:09
membertanweer akhtar29-Jun-12 2:09 
QuestionHi chris, Pin
rkasani.du7-Jun-12 21:12
memberrkasani.du7-Jun-12 21:12 
Bugselecting a table through text field and display it on another page Pin
Micah David9-May-12 8:12
memberMicah David9-May-12 8:12 
Newsinserting an image with a name text box to database Pin
Micah David9-May-12 8:07
memberMicah David9-May-12 8:07 
QuestionsThumbExtension Pin
_charM25-Apr-12 4:43
member_charM25-Apr-12 4:43 
QuestionDisplay images randomly on the basis of category Pin
SKapil20-Mar-12 4:41
memberSKapil20-Mar-12 4:41 
QuestionVijaykumar Pin
arulmurugan0925-Jan-12 3:12
memberarulmurugan0925-Jan-12 3:12 
QuestionBrilliant Demo for Uploading Image Pin
Vital896-Jan-12 20:10
memberVital896-Jan-12 20:10 
GeneralMy vote of 5 Pin
ahmadnaziF2-Jan-12 1:08
memberahmadnaziF2-Jan-12 1:08 
GeneralMy vote of 5 Pin
Nazeemabegum11-Nov-11 0:56
memberNazeemabegum11-Nov-11 0:56 
Questionimage upload using asp ans VB Pin
Noxy Thabethe5-Aug-11 15:37
memberNoxy Thabethe5-Aug-11 15:37 
Generalthumbnail image byte more than large files Pin
Seema Gosain28-May-11 21:51
memberSeema Gosain28-May-11 21:51 
GeneralMy vote of 5 Pin
sndpn4u22-Feb-11 20:50
membersndpn4u22-Feb-11 20:50 
GeneralMy vote of 1 Pin
jaya2chandra31-Jan-11 20:11
memberjaya2chandra31-Jan-11 20:11 
GeneralWith other images format Pin
buicongdang10-Aug-10 4:41
memberbuicongdang10-Aug-10 4:41 
GeneralSmall change suggested, if anybody has error as "the class doesnt exist" or something like that Pin
Gauri Vora2-Aug-10 19:57
memberGauri Vora2-Aug-10 19:57 
GeneralNewest not always best Pin
pathfinder800817-Jul-10 6:12
memberpathfinder800817-Jul-10 6:12 
GeneralMy vote of 4 Pin
Niranjan00111-Jul-10 21:08
memberNiranjan00111-Jul-10 21:08 
Generalduplicacy is not handled ma friend.. Pin
arvinder_aneja21-Jan-10 18:56
memberarvinder_aneja21-Jan-10 18:56 
GeneralRe: duplicacy is not handled ma friend.. Pin
Christian Graus25-Jan-10 20:05
mvpChristian Graus25-Jan-10 20:05 
GeneralRe: duplicacy is not handled ma friend.. Pin
arvinder_aneja1-Feb-10 0:22
memberarvinder_aneja1-Feb-10 0:22 
GeneralRe: duplicacy is not handled ma friend.. Pin
Christian Graus4-Feb-10 23:44
mvpChristian Graus4-Feb-10 23:44 
GeneralRe: duplicacy is not handled ma friend.. Pin
aspdotnetdev5-Feb-10 6:36
memberaspdotnetdev5-Feb-10 6:36 
GeneralRe: duplicacy is not handled ma friend.. Pin
John Simmons / outlaw programmer5-Feb-10 0:30
memberJohn Simmons / outlaw programmer5-Feb-10 0:30 
GeneralimageUrl Problem Pin
Chit Min Maung5-Jan-10 7:54
memberChit Min Maung5-Jan-10 7:54 
QuestionCould not load type 'WebForm1' Pin
jijo poulose25-Aug-09 20:48
memberjijo poulose25-Aug-09 20:48 
Questiondoubt in imgPicture Pin
preetha19857-Jul-09 22:45
memberpreetha19857-Jul-09 22:45 
GeneralAwesome yet make a li l ammendment Pin
demonizeddevil22-Jun-09 20:51
memberdemonizeddevil22-Jun-09 20:51 
GeneralRe: Awesome yet make a li l ammendment Pin
pathfinder800817-Jul-10 6:01
memberpathfinder800817-Jul-10 6:01 
GeneralVB Conversion Pin
bcalvin17-Apr-09 16:14
memberbcalvin17-Apr-09 16:14 
GeneralRe: VB Conversion Pin
theboyholty26-May-09 23:47
membertheboyholty26-May-09 23:47 
Generalrequest for vb code Pin
Diadems2720-Feb-09 13:07
memberDiadems2720-Feb-09 13:07 
QuestionBitmap ?? Pin
vaibhavbaweja13-Dec-08 2:50
membervaibhavbaweja13-Dec-08 2:50 
AnswerRe: Bitmap ?? Pin
neo822319-Dec-08 12:15
memberneo822319-Dec-08 12:15 
GeneralMultiple Image Upload in C# Pin
anandmmsoft12-Oct-08 20:33
memberanandmmsoft12-Oct-08 20:33 
GeneralThanks so much Pin
dcakmak17-Apr-08 10:14
memberdcakmak17-Apr-08 10:14 
Generalimages failed to load/display Pin
Thomas Toh15-Apr-08 19:07
memberThomas Toh15-Apr-08 19:07 
Generalthanks! Pin
xiazhi339-Apr-08 5:42
memberxiazhi339-Apr-08 5:42 
GeneralBetter way : Pin
m1234567gfd4-Jan-08 4:01
memberm1234567gfd4-Jan-08 4:01 
QuestionNot working with file size greater than 100 kb Pin
Jigs160218-Aug-07 23:33
memberJigs160218-Aug-07 23:33 
GeneralThanks for the article Pin
Boro_Bob26-Jul-07 21:08
memberBoro_Bob26-Jul-07 21:08 
Generalyou have error in code! Pin
masfenix3-Jun-07 13:35
membermasfenix3-Jun-07 13:35 
Questionkeeping aspect ratio Pin
jezh198623-Apr-07 13:59
memberjezh198623-Apr-07 13:59 
GeneralTo show 3 thumbs on screen Pin
sheebalam4-Mar-07 20:35
membersheebalam4-Mar-07 20:35 
GeneralJpg will not show on page reload! Pin
programmingAddict23-Feb-07 8:11
memberprogrammingAddict23-Feb-07 8:11 
GeneralThe type 'netimageupload.WebForm1' already contains a definition for 'filUpload' Pin
socalmp17-Dec-06 21:12
membersocalmp17-Dec-06 21:12 
GeneralExcelent friend!!! Pin
Vhakti14-Oct-06 13:12
memberVhakti14-Oct-06 13:12 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150804.2 | Last Updated 13 Mar 2002
Article Copyright 2002 by Chris Khoo
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid