BennoDual
BennoDual

Reputation: 6289

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:

How can I do this?

Thanks for your help.

Upvotes: 0

Views: 6620

Answers (2)

Hary
Hary

Reputation: 5818

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";
        }

    }
}

Upvotes: 1

dustyhoppe
dustyhoppe

Reputation: 1813

You should start with the ASP.NET FileUpload control. Here is a pretty good tutorial on how to complete this task.

Upvotes: 1

Related Questions