Search code examples
asp.netfile-uploadfile-browser

Browse and upload file


I have a ASP.NET (.NET Framework 3.5) Application. Now, I have to place a Button on a aspx-Page with the fallowing functionality on click:

  • Ask the user for a file with Extension xls (OpenFileDialog)
  • Upload the selected file to a specific folder on the WebServer

How can I do this?

Thanks for your help.


Solution

  • Here is the code that can be used for file upload after checking certain file types.

      protected void Upload_File() {
        bool correctExtension = false;
    
        if (FileUpload1.HasFile) {
            string fileName = FileUpload1.PostedFile.FileName;
            string fileExtension = Path.GetExtension(fileName).ToLower();
            string[] extensionsAllowed = {".xls", ".docx", ".txt"};
    
            for (int i = 0; i < extensionsAllowed.Length; i++) {
                if (fileExtension == extensionsAllowed[i]) {
                    correctExtension = true;
                }
            }
    
            if (correctExtension) {
                try {
                    string fileSavePath = Server.MapPath("~/Files/");
                    FileUpload1.PostedFile.SaveAs(fileSavePath + fileName);
                    Label1.Text = "File successfully uploaded";
                }
                catch (Exception ex) {
                    Label1.Text = "Unable to upload file";
                }
            }
            else {
                Label1.Text = "File extension " + fileExtension + " is not allowed";
            }
    
        }
    }