1.8. Upload Files to Your Web SiteASP.NET 2.0 now includes the FileUpload control, allowing web site users to upload files onto the web server for archival or file-submission purposes. For example, students typically need to upload their files to their school's server when they submit their assignment or project work. You'll find the FileUpload control in the Toolbox under the Standard tab. Note: Uploading files to your web site is made easy with the new FileUpload control. 1.8.1. How do I do that?The Visual Studio designer represents the FileUpload control by adding an empty text box and a Button control to a Web page. To upload the selected file, you need to explicitly trigger an event, such as clicking a button (see the Submit button in Figure 1-30). In the following example, you will build an application that allows users to upload files to a particular directory on the server. You will also check the size of the file uploaded to ensure that users do not upload files that exceed an imposed limit.
Tip: You use the FileUpload1.SaveAs( ) method to save the file onto the specified directory. If there is a file of the same name, this method will simply overwrite it with the new file. Hence it is important that you do some error checking before writing the file to the server.
You find out the path that the current application resides in by using the PhysicalApplicationPath property from the Request object. The HasFile property of the FileUpload control specifies if the user has selected a file to upload. The file selected is saved in the FileName property of the FileUpload control. 1.8.2. What about......limiting the size of uploaded files? For security reasons, it is important to restrict the size of files that users may upload to your web site. (Allowing users to upload a file that is too large could potentially expose an app to a denial-of-service attack.) You can check the size of the file uploaded by using the ContentLength property, as the following example shows: Note: Be sure to check the size of the file that your user is trying to upload. Failing to do so may allow users to upload large files thereby slowing (or crashing) your web server. ' ensure size if below 3MB If FileUpload1.PostedFile.ContentLength <= 3145728 Then savePath += FileUpload1.FileName ' existing file will be overwritten FileUpload1.SaveAs(savePath) Response.Write("File uploaded successfully!") Else Response.Write("File size exceeds 3MB.") End If 1.8.3. Where can I learn more?If you want to learn more about how file uploading is done in ASP.NET 1.x, check out this article: http://www.ondotnet.com/pub/a/dotnet/2002/04/01/asp.html. |