2011/02/26

Simple file upload by using FileUpload control.

What I need:
1.User can upload only one file at a time.
2.No save file to disk; read it's content and then dispose it.
3.Only txt and csv file types are allowed.

Here is the aspx page
<asp:Panel ID="PanelUploadList" runat="server" ViewStateMode="Disabled">
    <hr />
    Please select a text file to upload:
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:RequiredFieldValidator ID="RequiredFieldValidatorFileUpload" runat="server"
        ControlToValidate="FileUpload1"
        ErrorMessage="Please select a file to upload!" Display="Dynamic">*asp:RequiredFieldValidator>
    <asp:RegularExpressionValidator ID="RegularExpressionValidatorFileUpload" runat="server"
        ControlToValidate="FileUpload1" ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.txt|.csv)$"
        ErrorMessage="Only txt and csv file types are allowed!">*asp:RegularExpressionValidator>
    <asp:Button ID="ButtonUpload" runat="server" OnClick="ButtonUpload_Click"
        Text="Upload" />
    <hr />
</asp:Panel>

Here is the code behind
static object LockMe = new object();

protected void ButtonUpload_Click(object sender, EventArgs e)
{
    lock (LockMe)   //For Thread-Safe.
    {
        if (FileUpload1.HasFile)
        {
            if (Path.GetExtension(FileUpload1.FileName).ToLower().Contains(".txt") || Path.GetExtension(FileUpload1.FileName).ToLower().Contains(".csv"))
            {
                string FilePath = FileUpload1.FileName;
                string[] FileContentArray;

                using (StreamReader sr = new StreamReader(FileUploadCompanyList.FileContent))
                {
                    FileContentArray = sr.ReadToEnd().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                }

                List<int> IDList = CheckAndSortStringArray(FileContentArray);

                if (IDList.Count > 0)
                {
                    //Your codes here.
                }
                else
                {
                    //Error handling

                 }
            }
            else
                //Show to user that "Only txt and csv file types are allowed!" message.
        }
        else
        {
            //Show to user that "Please select a file!" message.
        }
    }
}

No comments:

Post a Comment