ASP.NET 2.0 File Upload Server Control

ASP.NET 2.0 introduces a File Upload server control that makes uploading files to a server simpler. While a page starts to upload files, just include <asp:FileUpload ID="FileUpload1" runat="server" /> control. ASP.NET makes the rest of the process simpler, while adding of enctype attribute to the page's <form> element.

Uploading Files Using the File Upload Control

When a file gets uploaded into the server, you may add up to 5 files using upload control by the ‘Add More’ button.


This figure shows an example of using the File Upload control.

This page contains a single File Upload control, an Upload Button and a label.

Uploading Multiple Files from the Same Page

You can build an ASP.NET page that has Five File Upload controls and one Add More button (using the Button control). When the user clicks the Upload button and the files are posted to the server, the code saves the files to a specific location on the server.



 






By using the code given below, we can add five file uploads in ASP.NET page.

<script type="text/javascript" language="javascript" >

                                      function popVisible()

                                      {

                                     

                                       if(document.getElementById('file2').style.display =="none")

                                      {

                            

                                      document.getElementById('file2').style.display ="block";

                                     

                                      }

                                      else  if(document.getElementById('file2').style.display =="block")

                                      {

                                                 if(document.getElementById('file3').style.display =="block")

                                      {

                                                 if(document.getElementById('file4').style.display =="block")

                                      {

                                               

                                      document.getElementById('file5').style.display ="block";

                                     

                                      }

                                      document.getElementById('file4').style.display ="block";

                                     

                                      }

                                      document.getElementById('file3').style.display ="block";

                                     

                                      }

                                                                                     

                                     

                   return false;

             }

</ script >

 

 

Html page shows:

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Multi FileUpload</title>

</head>

<body>

    <form id="form1" runat="server">

   <div><asp:Label ID="lblimage" runat="server" Text="" ForeColor="red"></asp:Label></div>

    <div>Select up to five images to upload,up to total of 5 MB<br /></div>

    <div>

 

                   <div id="file1" runat="server">

                   <asp:FileUpload ID="Fileimage1" runat="server" />&nbsp;<asp:Button ID="btnAdd"

                   runat="server"  Text="Add More" OnClientClick="javascript:return popVisible();"  /></div>

           

           

                         <div id="file2" style="display:none;">

                <asp:FileUpload ID="Fileimage2" runat="server" /></div>

                   

                             <div  id="file3" style="display:none;" >

                <asp:FileUpload ID="Fileimage3" runat="server" /></div>

                   

                         <div id="file4" style="display:none;">

                <asp:FileUpload ID="Fileimage4" runat="server" /></div>

                   

                        <div id="file5" style="display:none;">

                <asp:FileUpload ID="Fileimage5" runat="server" /></div>

           

          

      

          

     </div><div><asp:Button ID="btnUpload"

            runat="server"  Text="Upload" OnClick="btnUpload_Click"/>

         <input id="Reset1" type="reset" value="Reset" /></div>

    </form>

</body>

 

Once the file is uploaded, the first check is to (carried out  in the file's btnupload_Click event handler) verify  whether a reference of a file  is actually placed within the <input type="file"> element or not. If a file is specified, an attempt is then made to upload the file to the server using ‘Save As’ in the File Upload control. It takes a single String parameter that includes the location where you want to save the file. The file will be saved to a folder called Uploads, which is located in the User Photo Folder

‘The PostedFile.FileName’ will give the saved file the same name as the file it was copied from. If you want to rename the file, simply use the ‘Save As’ method in the following manner:

 Fileimage1.SaveAs(filePath1);

Code Behind Asp.net page:

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.IO;

using System.Drawing.Imaging;

using System.Drawing;

public partial class _Default : System.Web.UI.Page

{

    ImageResize imgresize = new ImageResize();

    protected void Page_Load(object sender, EventArgs e)

    {

        btnUpload.Attributes.Add("OnClick", "javascript:return checkform();");

    }

    public void processImage2(string fileName, string imagePath)

    {

        Bitmap image = new Bitmap(imagePath);

        imgresize.CreateThumbNail(image, Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["SmallWidth"].ToString()), Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["SmallHeight"].ToString())).Save(Server.MapPath(".") + "\\UserPhoto\\Small\\" + fileName);

        image.Dispose();

        new FileInfo(imagePath).Delete();

    }

    public void processImage1(string fileName, string imagePath)

    {

        Bitmap image = new Bitmap(imagePath);

        imgresize.CreateThumbNail(image, Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["LargeWidth"].ToString()), Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["LargeHeight"].ToString())).Save(Server.MapPath(".") + "\\UserPhoto\\Enlarge\\" + fileName);

        image.Dispose();

        new FileInfo(imagePath).Delete();

    }

 

    protected void btnUpload_Click(object sender, EventArgs e)

    {

        string imageExtLarge = "";

        string imageExtSmall = "", ImgDate = "";

        ImgDate = DateTime.Now.ToString().Replace(" ", "").Replace("/", "").Replace(":", "");

        if (Fileimage1.HasFile)

        {

            lblimage.Text = "";

            imageExtLarge = "Photo1" + ImgDate.ToString() + Path.GetExtension(Fileimage1.PostedFile.FileName);

            string filePath1 = Server.MapPath(".") + "//UserPhoto//Enlarge//" + Fileimage1.FileName;

            Fileimage1.SaveAs(filePath1);

            processImage1(imageExtLarge, filePath1);

            imageExtSmall = "Photo1" + ImgDate.ToString() + Path.GetExtension(Fileimage1.PostedFile.FileName);

            string filePath2 = Server.MapPath(".") + "//UserPhoto//Small//" + Fileimage1.FileName;

            Fileimage1.SaveAs(filePath2);

            processImage2(imageExtSmall, filePath2);

            PhotoGallary.ImageInsert(0, 0, imageExtLarge.ToString(), 1);

        }

 

 

        if (Fileimage2.HasFile)

        {

            lblimage.Text = "";

            imageExtLarge = "Photo2" + ImgDate.ToString() + Path.GetExtension(Fileimage2.PostedFile.FileName);

            string filePath1 = Server.MapPath(".") + "//UserPhoto//Enlarge//" + Fileimage2.FileName;

            Fileimage2.SaveAs(filePath1);

            processImage1(imageExtLarge, filePath1);

            imageExtSmall = "Photo2" + ImgDate.ToString() + Path.GetExtension(Fileimage2.PostedFile.FileName);

            string filePath2 = Server.MapPath(".") + "//UserPhoto//Small//" + Fileimage2.FileName;

            Fileimage2.SaveAs(filePath2);

            processImage2(imageExtSmall, filePath2);

            PhotoGallary.ImageInsert(0, 0, imageExtLarge.ToString(), 1);

        }

 

 

        if (Fileimage3.HasFile)

        {

 

            lblimage.Text = "";

            imageExtLarge = "Photo3" + ImgDate.ToString() + Path.GetExtension(Fileimage3.PostedFile.FileName);

            string filePath1 = Server.MapPath(".") + "//UserPhoto//Enlarge//" + Fileimage3.FileName;

            Fileimage3.SaveAs(filePath1);

            processImage1(imageExtLarge, filePath1);

            imageExtSmall = "Photo3" + ImgDate.ToString() + Path.GetExtension(Fileimage3.PostedFile.FileName);

            string filePath2 = Server.MapPath(".") + "//UserPhoto//Small//" + Fileimage3.FileName;

            Fileimage3.SaveAs(filePath2);

            processImage2(imageExtSmall, filePath2);

            PhotoGallary.ImageInsert(0, 0, imageExtLarge.ToString(), 1);

        }

 

        if (Fileimage4.HasFile)

        {

 

            lblimage.Text = "";

 

            imageExtLarge = "Photo4" + ImgDate.ToString() + Path.GetExtension(Fileimage4.PostedFile.FileName);

            string filePath1 = Server.MapPath(".") + "//UserPhoto//Enlarge//" + Fileimage4.FileName;

            Fileimage4.SaveAs(filePath1);

            processImage1(imageExtLarge, filePath1);

            imageExtSmall = "Photo4" + ImgDate.ToString() + Path.GetExtension(Fileimage4.PostedFile.FileName);

            string filePath2 = Server.MapPath(".") + "//UserPhoto//Small//" + Fileimage4.FileName;

            Fileimage4.SaveAs(filePath2);

            processImage2(imageExtSmall, filePath2);

            PhotoGallary.ImageInsert(0, 0, imageExtLarge.ToString(), 1);

        }

 

        if (Fileimage5.HasFile)

        {

 

            lblimage.Text = "";

            imageExtLarge = "Photo5" + ImgDate.ToString() + Path.GetExtension(Fileimage5.PostedFile.FileName);

            string filePath1 = Server.MapPath(".") + "//UserPhoto//Enlarge//" + Fileimage5.FileName;

            Fileimage5.SaveAs(filePath1);

            processImage1(imageExtLarge, filePath1);

            imageExtSmall = "Photo5" + ImgDate.ToString() + Path.GetExtension(Fileimage5.PostedFile.FileName);

            string filePath2 = Server.MapPath(".") + "//UserPhoto//Small//" + Fileimage5.FileName;

            Fileimage5.SaveAs(filePath2);

            processImage2(imageExtSmall, filePath2);

            PhotoGallary.ImageInsert(0, 0, imageExtLarge.ToString(), 1);

        }

 

        if(!Fileimage1.HasFile && !Fileimage2.HasFile && !Fileimage3.HasFile && !Fileimage4.HasFile && !Fileimage5.HasFile )

        {

            lblimage.Text = "Plese select photo for upload";

        }

 

   

    }

   

}

For Image resize using code:

 

using System;

using System.Collections.Generic;

using System.Text;

using System.Drawing;

using System.IO;

using System.Drawing.Imaging;

using System.Drawing.Drawing2D;

 

/// <summary>

/// Summary description for ImageResize

/// </summary>

public class ImageResize

{

    public System.Drawing.Image ScaleByPercent(System.Drawing.Image imgPhoto, float Percent, int targetCanvasWidth, int targetCanvasHeight)

    {

        float nPercent = (((float)(Percent)) / 100);

        int sourceWidth = imgPhoto.Width;

        int sourceHeight = imgPhoto.Height;

        int sourceX = 0;

        int sourceY = 0;

        int destWidth = ((int)((sourceWidth * nPercent)));

        int destHeight = ((int)((sourceHeight * nPercent)));

        int destX = (targetCanvasWidth - destWidth) / 2;

        int destY = (targetCanvasHeight - destHeight) / 2;

        Bitmap bmPhoto = new Bitmap(targetCanvasWidth, targetCanvasHeight, PixelFormat.Format24bppRgb);

        bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

        Graphics grPhoto = Graphics.FromImage(bmPhoto);

        grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

        grPhoto.Clear(System.Drawing.Color.FromArgb(34, 54, 70));

        grPhoto.DrawImage(imgPhoto, new Rectangle(destX, destY, destWidth, destHeight), new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel);

        grPhoto.Dispose();

        return bmPhoto;

    }

    public System.Drawing.Image CreateThumbNail(Bitmap postedFile, int width, int height)

    {

 

        System.Drawing.Image imgBanner;

        ImageFormat Format = postedFile.RawFormat;

        Decimal Ratio;

        int NewWidth;

        int NewHeight;

        // *** If the image is smaller than a thumbnail just return it

 

        if ((postedFile.Width > postedFile.Height))

        {

            Ratio = Convert.ToDecimal((Convert.ToDecimal(width) / postedFile.Width));

            NewWidth = width;

            Decimal Temp = (postedFile.Height * Ratio);

            NewHeight = Convert.ToInt32(Temp);

        }

        else

        {

            Ratio = Convert.ToDecimal((Convert.ToDecimal(height) / postedFile.Height));

            NewHeight = height;

            Decimal Temp = (postedFile.Width * Ratio);

            NewWidth = Convert.ToInt32(Temp);

        }

        float per = (float)(Ratio * 100);

 

        imgBanner = NewScaleByPercent(postedFile, per, width, height);

        return imgBanner;

    }

    public static System.Drawing.Image NewScaleByPercent(System.Drawing.Image imgPhoto, float Percent, int targetCanvasWidth, int targetCanvasHeight)

    {

        float nPercent = ((float)Percent / 100);

 

        int sourceWidth = imgPhoto.Width;

        int sourceHeight = imgPhoto.Height;

        int sourceX = 0;

        int sourceY = 0;

 

        int destWidth = (int)(sourceWidth * nPercent);

        int destHeight = (int)(sourceHeight * nPercent);

        int destX = (targetCanvasWidth - destWidth) / 2;

        int destY = (targetCanvasHeight - destHeight) / 2;

 

        Bitmap bmPhoto = new Bitmap(targetCanvasWidth, targetCanvasHeight, PixelFormat.Format24bppRgb);

        bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

 

        Graphics grPhoto = Graphics.FromImage(bmPhoto);

        grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

        grPhoto.Clear(Color.White);

 

        grPhoto.DrawImage(imgPhoto,

            new Rectangle(destX, destY, destWidth, destHeight),

            new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),

            GraphicsUnit.Pixel);

 

        grPhoto.Dispose();

        return bmPhoto;

    }

}

 

 

 

Giving ASP.NET Proper Permissions to Upload Files

You might receive errors when end users upload files to your Web server through the File Upload control in your application. These might occur because the destination folder on the server is not writable for the account used by ASP.NET. If ASP.NET is not enabled to write to the folder you need, you may enable it using the folder's properties.

First, right-click on the folder where the ASP.NET files should be uploaded and select Properties from the provided menu. The Properties dialog box for the selected folder opens. Click the Security tab to make sure the ASP.NET Machine Account is included in the list and has the proper permission to write to the disk. If it is enabled, you see something similar to what is represented in Figure 2.

Figure 2.

 

 

 

Understanding File Size Limitations

Your end users might never encounter an issue with the file upload process in your application, but you should be aware that some limitations always exist. When users work through the process of uploading files, a check on file size is sent to the server for uploading. The default size limit is 5MB (5120KB); the transfer fails if a user tries to upload a file that is larger than 5120KB.

The  size restriction protects your application from errors. You can prevent malicious users from uploading numerous large files to your Web server and thereby attempting to tie up all the available processes on the server. Such an instance is termed as "denial of service attack". It may disrupt the whole process.

Besides, it can also tie up the Web server's resources so that even legitimate users are denied responses from the server.

. NET being a user-friendly platform, has easily manageable options to provide a way around its limitations. To change the limit on the allowable upload file size, you can make some changes either in the web.config.comments file (found in the ASP.NET 2.0 configuration folder at C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG) or in your application's web.config file.

In the web.config.comments file, find <httpRuntime> node.

In this file, you can find out that the default allowable file size is dictated by the actual request size permitted to the Web server (5120KB).

The <httpRuntime> section of the web.config.comments file is shown in Listing 2.

Listing 2: Changing the File Size Limitation Setting in the web.config File

 

http://www.codeproject.com/images/minus.gifCollapse

<httpRuntime 
 executionTimeout="138" 
 maxRequestLength="5120" 
 requestLengthDiskThreshold="80" 
 useFullyQualifiedRedirectUrl="false" 
 minFreeThreads="8" 
 minLocalRequestFreeThreads="4" 
 appRequestQueueLimit="5000" 
 enableKernelOutputCache="true" 
 enableVersionHeader="true" 
 requireRootedSaveAsPath="true" 
 enable="true" 
 shutdownTimeout="90" 
 delayNotificationTimeout="5" 
 waitChangeNotification="0" 
 maxWaitChangeNotification="0" 
 enableHeaderChecking="true" 
 sendCacheControlHeader="true" 
 apartmentThreading="false" />

You can make use of the <httpRuntime> section of the web.config file, but two properties — the maxRequestLength and executionTimeout properties — are especially interesting.

The maxRequestLength property is the setting that dictates the size of the request made to the Web server. When you upload files, the file is included in the request; you can alter the size allowed to be uploaded by changing the value of this property. This value is given in kilobytes. To allow files larger than the default 5MB, change the maxRequestLength property as in the following: maxRequestLength="11000".

This example changes the maxRequestLength. The  value  can be set up to 11,000KB (around 10MB). With this setting in place, your end users can upload 10MB files to the server. On changing the maxRequestLength property, one must be careful about  the setting provided for the executionTimeout property. This property sets the time (in seconds) for a request to attempt to execute the operation before ASP.NET shuts down the request (whether or not it is finished). The default setting is pitched at 90 seconds. The end user receives a timeout error notification in the browser if the time limit is exceeded.

If you are going to permit larger requests, remember that they take longer to execute than smaller ones. If you increase the size of the maxRequestLength property, care should be taken to increase the executionTimeout property as well.

If you are working with smaller files, it's advisable to reduce the size allotted for the request to the Web server by decreasing the value of the maxRequestLength property. This helps safeguard your application from a denial of service attack.

Making these changes in the web.config.comments file applies this setting to all the applications that are on the server. but If you want to apply this change only to the application you are working with, apply the <httpRuntime> node to the web.config file of your application, overriding any setting that is in the web.config.comments file. Make sure this node resides between the <system.web> nodes in the configuration file.

Tags:

View Live Demo Download Source

Back to Main Top of Page

Search Resources

Subscribe Free Resource