5,316,870 members and growing! (17,078 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Intermediate

.NET Image Uploading

By Chris Khoo

Uploading images in .NET and thumbnailing, resizing, etc.
C#, .NET, Win2K, WinXP, Windows, Visual Studio, ASP.NET, Dev

Posted: 12 Mar 2002
Updated: 12 Mar 2002
Views: 267,154
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
40 votes for this Article.
Popularity: 6.91 Rating: 4.31 out of 5
3 votes, 8.1%
1
0 votes, 0.0%
2
3 votes, 8.1%
3
9 votes, 24.3%
4
22 votes, 59.5%
5

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. :-)

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

About the Author

Chris Khoo


Working in Brisbane, Australia - currently into .NET 3.5 (WPF & WF especially).
Occupation: Web Developer
Location: Australia Australia

Other popular ASP.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 70 (Total in Forum: 70) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralThanks so muchmemberdcakmak11:14 17 Apr '08  
Generalimages failed to load/displaymemberThomas Toh20:07 15 Apr '08  
Generalthanks!memberxiazhi336:42 9 Apr '08  
GeneralBetter way :memberm1234567gfd5:01 4 Jan '08  
QuestionNot working with file size greater than 100 kbmemberJigs16020:33 19 Aug '07  
GeneralThanks for the articlememberBoro_Bob22:08 26 Jul '07  
Generalyou have error in code!membermasfenix14:35 3 Jun '07  
Questionkeeping aspect ratiomemberjezh198614:59 23 Apr '07  
GeneralTo show 3 thumbs on screenmembersheebalam21:35 4 Mar '07  
GeneralJpg will not show on page reload!memberprogrammingAddict9:11 23 Feb '07  
GeneralThe type 'netimageupload.WebForm1' already contains a definition for 'filUpload'membersocalmp22:12 17 Dec '06  
GeneralExcelent friend!!!memberVhakti14:12 14 Oct '06  
GeneralLooking for an alternatememberGazzooks10:47 26 Sep '06  
GeneralTry this Solutionmemberbritneyssssers4:12 8 Sep '06  
GeneralEXCELLENT ARTICLE!memberFlashMerlot3:57 3 Jul '06  
QuestionHow it works with DataGrid Template?..memberArnLee1021:22 9 Apr '06  
GeneralRe: How it works with DataGrid Template?..memberamit m1:06 22 May '08  
GeneralSimpler waymemberPhil Rounds12:23 2 Feb '06  
GeneralThe easiest way to upload and resize your images to the internet.memberzioturo23:30 1 Nov '05  
GeneralProblem with larger filesmembervirsum10:07 1 Oct '05  
GeneralRe: Problem with larger filesmemberserguey_haftrige23:06 22 Oct '05  
GeneralRe: Problem with larger filesmembervillian158:19 24 Apr '06  
Generalupload all files from specify foldermembersachin wani3:03 22 Aug '05  
Generalcan not upload image,sussAnonymous4:52 17 Aug '05  
GeneralRe: can not upload image,memberDanny__T16:02 17 Sep '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 12 Mar 2002
Editor: Chris Maunder
Copyright 2002 by Chris Khoo
Everything else Copyright © CodeProject, 1999-2008
Web13 | Advertise on the Code Project