Click here to Skip to main content
15,867,330 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 808.6K   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

 
GeneralThe type 'netimageupload.WebForm1' already contains a definition for 'filUpload' Pin
socalmp17-Dec-06 21:12
socalmp17-Dec-06 21:12 
GeneralExcelent friend!!! Pin
Vhakti14-Oct-06 13:12
Vhakti14-Oct-06 13:12 
GeneralLooking for an alternate Pin
Gazzooks26-Sep-06 9:47
Gazzooks26-Sep-06 9:47 
GeneralTry this Solution Pin
Britney S. Morales8-Sep-06 3:12
Britney S. Morales8-Sep-06 3:12 
GeneralEXCELLENT ARTICLE! Pin
FlashMerlot3-Jul-06 2:57
FlashMerlot3-Jul-06 2:57 
QuestionHow it works with DataGrid Template?.. Pin
ArnLee109-Apr-06 20:22
ArnLee109-Apr-06 20:22 
GeneralRe: How it works with DataGrid Template?.. Pin
amit m22-May-08 0:06
amit m22-May-08 0:06 
GeneralSimpler way Pin
Phil Rounds2-Feb-06 11:23
Phil Rounds2-Feb-06 11:23 
GeneralThe easiest way to upload and resize your images to the internet. Pin
zioturo1-Nov-05 22:30
zioturo1-Nov-05 22:30 
RantRe: The easiest way to upload and resize your images to the internet. Pin
graham_m4-Mar-10 2:02
graham_m4-Mar-10 2:02 
GeneralRe: The easiest way to upload and resize your images to the internet. Pin
zioturo4-Mar-10 2:36
zioturo4-Mar-10 2:36 
GeneralProblem with larger files Pin
virsum1-Oct-05 9:07
virsum1-Oct-05 9:07 
GeneralRe: Problem with larger files Pin
serguey_haftrige22-Oct-05 22:06
serguey_haftrige22-Oct-05 22:06 
GeneralRe: Problem with larger files Pin
villian1524-Apr-06 7:19
villian1524-Apr-06 7:19 
Generalupload all files from specify folder Pin
Member 221305322-Aug-05 2:03
Member 221305322-Aug-05 2:03 
Questioncan not upload image, Pin
Anonymous17-Aug-05 3:52
Anonymous17-Aug-05 3:52 
AnswerRe: can not upload image, Pin
Danny__T17-Sep-05 15:02
Danny__T17-Sep-05 15:02 
Generali fail to run this example,,, Pin
s_p15-Aug-05 5:53
s_p15-Aug-05 5:53 
AnswerRe: i fail to run this example,,, Pin
virsum1-Oct-05 8:52
virsum1-Oct-05 8:52 
GeneralCouldn't run the example! Pin
jeliaq3-Jul-05 18:05
jeliaq3-Jul-05 18:05 
QuestionI want to upload into sql database. how? Pin
Jansen Chua31-Jan-05 4:54
sussJansen Chua31-Jan-05 4:54 
AnswerRe: I want to upload into sql database. how? Pin
JordanGRE27-Apr-05 7:11
sussJordanGRE27-Apr-05 7:11 
GeneralThumbnail Dimmensions Pin
klokanek_votrubu8-Dec-04 10:23
klokanek_votrubu8-Dec-04 10:23 
GeneralRe: Thumbnail Dimmensions Pin
iCanoe23-Mar-05 4:51
iCanoe23-Mar-05 4:51 
GeneralRe: Thumbnail Dimmensions Pin
iCanoe23-Mar-05 5:54
iCanoe23-Mar-05 5:54 

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.