Friday, July 23, 2010

How to upload a file – Asp.net

When uploading a file there are two main concerns.
  1. Do we have correct permissions to the directory? Asp.net work process should have write permissions to the upload directory in-order to save the uploaded file.
  2. The file size that we try to upload, does it exceed the allowed request limit of by the .net runtime? This example allows requests smaller than 2 MB (2024 KB)
<system.web>
  <httpRuntime maxRequestLength="2024" />
In this case provide a suitable error message for error 404.13
Here is a complete example to demonstrate how to upload a file using asp.net
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head2" runat="server">
        <script runat="server">
            string uploadPath = "Uploads";
            public void Save(object sender, EventArgs e)
            {
                if (this.fuFile.HasFile)
                {
                    string filepath = Server.MapPath(Path.Combine(this.uploadPath, this.fuFile.FileName));
                    if (!File.Exists(filepath))
                    {
                        this.fuFile.SaveAs(filepath);
                        this.lblResults.Text = "File uploaded successfully";
                    }
                    else
                        this.lblResults.Text = "File already exists";
                }
                else
                    this.lblResults.Text = "Please slect a file";
            }        
        </script>
    </head>
    <body>
        <form id="form2" runat="server">
        <div>
            <asp:FileUpload runat="server" ID="fuFile" />
            <asp:Button runat="server" ID="btnSave" OnClick="Save" Text="Save" />
            <asp:Label runat="server" ID="lblResults" />
        </div>
        </form>
    </body>
</html> 

2 comments:

Unknown said...

I hope the file extension will be .aspx. Am I correct?

Charith Shyam Gunasekara said...

Yes it is... but this does not use a HttpHandler

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...