Create an upload new page in asp.net
Here is an example of how to create an "Upload New" page in ASP.NET:
Step 1: Create a new ASP.NET Web Forms project
- Open Visual Studio and create a new project by selecting "ASP.NET Web Application" under the "Web" section.
- Name your project, for example, "UploadNewPage".
- Choose the ".NET Framework" version you want to use (e.g. 4.7.2).
- Click "OK" to create the project.
Step 2: Create a new ASPX page
- In the Solution Explorer, right-click on the project and select "Add" > "New Item...".
- In the "Add New Item" dialog box, select "Web Form" under the "Web" section.
- Name your page, for example, "UploadNew.aspx".
- Click "Add" to create the page.
Step 3: Design the page
- Open the "UploadNew.aspx" page in the designer.
- Drag and drop a "FileUpload" control from the Toolbox onto the page.
- Set the "ID" property of the FileUpload control to "fileUpload1".
- Drag and drop a "Button" control from the Toolbox onto the page.
- Set the "ID" property of the Button control to "btnUpload".
- Set the "Text" property of the Button control to "Upload".
- Drag and drop a "Label" control from the Toolbox onto the page.
- Set the "ID" property of the Label control to "lblMessage".
Step 4: Write the code-behind
-
Open the "UploadNew.aspx.cs" file in the code-behind.
-
Add the following code to handle the Button click event:
protected void btnUpload_Click(object sender, EventArgs e) { if (fileUpload1.HasFile) { string fileName = fileUpload1.FileName; string fileExtension = Path.GetExtension(fileName); string filePath = Server.MapPath("~/Uploads/") + fileName; fileUpload1.SaveAs(filePath); lblMessage.Text = "File uploaded successfully!"; } else { lblMessage.Text = "Please select a file to upload."; } }
This code checks if a file has been selected, and if so, saves the file to a directory called "Uploads" in the root of the project. It also displays a success message or an error message depending on whether the file was uploaded successfully.
Step 5: Add a directory for uploaded files
- In the Solution Explorer, right-click on the project and select "Add" > "New Folder...".
- Name the folder "Uploads".
- Set the "Build Action" property of the folder to "Content".
Step 6: Test the page
- Run the project by pressing F5 or clicking the "Debug" button.
- Open the "UploadNew.aspx" page in a web browser.
- Select a file to upload and click the "Upload" button.
- Verify that the file is uploaded successfully and the success message is displayed.
That's it! You now have an "Upload New" page in ASP.NET that allows users to upload files to a directory in the project.