2 ways to upload file in ASP.NET

Sourav.Kayal
Posted by in C# category on for Beginner level | Points: 250 | Views : 2266 red flag

This article will describe two different ways to upload file in asp.net

2 ways to upload file in ASP.NET C#

Dear reader, In this article we are going to look into two different style to upload file in asp.net application. In first approach, we will see traditional way to upload file using asp.net file uploader control and in second approach we will see how to implement asynchronous file uploading using AJAX. 

Let’s start with first approach.

Upload file using file uploader

This is traditional way to upload file . We will drag and drop file uploader control and in buttons click we will write code to upload file. Here is code for aspx page.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="InFileSystem.aspx.cs" Inherits="InFileSystem" %>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    </form>
</body>
</html>
 

For sake of simplicity whole C# page code is not posted. Just keep those few line in upload button’s click event.

protected void Button1_Click(object
sender, EventArgs e)
    {
  String Filename = FileUpload1.PostedFile.FileName;
        if (this.FileUpload1.HasFile)
        {
            FileUpload1.SaveAs(Server.MapPath("Uploads/") + Filename);
Response.Write("File Uploaded");
        }
    } 

And don’t forget to create Uploads folder under your root directory. And after uploading any file you will find the uploaded file in Uploads directory.

This is traditional approach to upload file. In next example we will see how to implement asynchronous file upload using ajax. 


Upload file using AJAX File Uploader Control

Before go through of this part I will recommend you to get basic idea of ajax in asp.net if you don’t have still. Here I will show how to implement asynchronous file uploader using asp.net ajax. Let’s start and see how to do that?

Here is my .aspx page .

 <%@
Page Language="C#" AutoEventWireup="true" 
CodeFile="CS.aspx.cs"
Inherits="_Default"
%>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
   <script type = "text/javascript">
        function uploadComplete(sender) {
            clearContents(sender._element.id);
        }
        function clearContents(id) {
            var AsyncFileUpload = $get(id);
            var txts = AsyncFileUpload.getElementsByTagName("input");
            for(var i = 0; i < txts.length; i++) {
                if(txts[i].type == "text") {
                    txts[i].value = "";
txts[i].style.backgroundColor = "white";
                }
            }
        }
       
        function uploadError(sender, args) {
               alert("File not supported");
        }
 
        function uploadStart(sender, args)
            {
            var filename = args.get_fileName();
            var filext = filename.substring(filename.lastIndexOf(".")+ 1);
            if(filext == "jpg" || filext == "gif" || filext == "png")
            {
                return true;
            }
            else{
                var err = new Error();
                err.name = 'My API Input Error';
                err.message = 'Only .jpg, .gif, .png files';
                throw(err);
                return false;
            }
        }
 
</script>
 
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <cc1:AsyncFileUpload
           
            OnClientUploadStarted="uploadStart"
            OnClientUploadError="uploadError"
            OnClientUploadComplete="uploadComplete"
            OnUploadedComplete = "FileUploadComplete"
 
            runat="server" ID="AsyncFileUpload1" Width="302px" UploaderStyle="Modern"
            CompleteBackColor = "White"
            UploadingBackColor="#CCFFFF" ThrobberID="imgLoader"
            Height="23px"
           
        />
        <asp:Image ID="imgLoader" runat="server" ImageUrl= "~/images/loader.gif"/>
        <br />
       <asp:Label ID="lblMesg" runat="server" Text=""></asp:Label>
    </form>
</body>
</html>
 

 If you observe this code you will find in uploadStart() function is to check the file type. Currently it will allow to upload only image type . So according to your need you can tune up that function.

And please don’t forget to register ajax control in your current aspx page by writing below line

 <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

in head section in aspx page. Now we will see content of .CS file. In below I have given code for saving uploaded file in folder.

  protected void FileUploadComplete(object sender, EventArgs e)
    {
        string filename  = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
        AsyncFileUpload1.PostedFile.SaveAs(Server.MapPath("Uploads/") + filename);
    }

And again please don’t forget to Create Uploaded folder in your root directory. 


Page copy protected against web site content infringement by Copyscape

About the Author

Sourav.Kayal
Full Name: Sourav Kayal
Member Level: Silver
Member Status: Member,MVP
Member Since: 6/20/2013 2:09:01 AM
Country: India
Read my blog here http://ctrlcvprogrammer.blogspot.in/
http://www.dotnetfunda.com
I am .NET developer working for HelixDNA Technologies,Bangalore in healthcare domain. Like to learn new technology and programming language. Currently working in ASP.NET ,C# and other microsoft technologies.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)