Demonstration for web-based upload in ASP.Net

2008-10-08

The code is extracted from part of my data transfer application. It demonstrates how to perform the following tasks in ASP.Net:

1. Web-based upload
2. File type validation
3. File renaming on timestamp
 

<%@ Page Language="C#" %>
<script runat="server">
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string fileExt = System.IO.Path.GetExtension(FileUpload1.FileName);
            string timestamp = DateTime.Now.ToString("yyyyMMddhhmmss");
            if (fileExt.ToLower() == ".xls")
            {
                try
                {
                    string filename = Server.MapPath("") + "\\spreadsheet" + timestamp + ".xls";
                    FileUpload1.SaveAs(filename);  

                    lblMessage.Text = "File name: " +
                         FileUpload1.PostedFile.FileName + "<br>" +
                         "File name on the server: " + filename + "<br>" +
                         FileUpload1.PostedFile.ContentLength + " kb<br>" +
                         "Content type: " +
                         FileUpload1.PostedFile.ContentType + "<br><font color='red'><strong>Spreadsheet upload is completed!</strong></font><br>";
                }
                catch (Exception ex)
                {
                    lblMessage.Text = "ERROR: " + ex.Message.ToString();
                }
            }
            else
                lblMessage.Text = "Only .xls files allowed!";
        }
        else
        {
            lblMessage.Text = "You have not specified a file.";
        }
    }
</script>
<html>
<head>
    <title>Spreadsheet upload demonstration</title>
    <style type="text/css">
        body, input {font-size:10px; font-family: Trebuchet MS;}
    </style>
</head>
<body>
    <form id="form1" runat="server">
        Your spreadsheet file: <asp:FileUpload ID="FileUpload1" runat="server" Width="300" />
        <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click"
         Text="Upload File" /><br />
          <asp:Label ID="lblMessage" runat="server"/>
    </form>
</body>
</html>

Previous Article:
Solution for database execution timeout problem in ASP.Net application


Next Article:
Transfer data from Excel to MS SQL in ASP.Net



Categories

Search eGaWa.Blog

Keyword 1
Keyword 2
Keyword 3
Category
Search

Search Web

Reload Page