Allowing File Uploads
The File Upload Control Fortunately, ASP.NET includes a control that allows website users to upload files to the web server. Once the web server receives the posted file data, it’s up to your application to examine it, ignore it, or save it to a back-end database or a file on the web server. The FileUpload control does this work, and it represents the <input type="file"> HTML tag. Declaring the FileUpload control is easy. It doesn’t expose any new properties or eventsyou can use through the control tag: <asp:FileUpload ID="Uploader" runat="server" />
The File Upload Control Contd. The <input type="file"> tag doesn’t give you much choice as far as user interface is concerned (it’s limited to a text box that contains a file name and a Browse button). When the user clicks Browse, the browser presents an Open dialog box and allows the user to choose a file. This part is hard-wired into the browser, and you can’t change this behavior. Once the user selects a file, the file name is filled into the corresponding text box. However, the file isn’t uploaded yet—that happens later, when the page is posted back. At this point, all the data from all input controls (including the file data) is sent to the server. For that reason, it’s common to add a button to post back the page. To get information about the posted file content, you can access the FileUpload.PostedFile object. You can save the content by calling the PostedFile.SaveAs() method: Uploader.PostedFile.SaveAs(@"c:\Uploads\newfile");
An example which accepts .bmp, .gif and .jpg extensions We have three components on the aspx page: A File Upload Control named Uploader. A Button Control named Upload. A Label Control named lblInfo.
An example which accepts .bmp, .gif and .jpg extensions public partial class UploadFile : System.Web.UI.Page { private string uploadDirectory; protected void Page_Load(object sender, EventArgs e) // Place files in a website subfolder named Uploads. uploadDirectory = Path.Combine( Request.PhysicalApplicationPath, "Uploads"); } protected void cmdUpload_Click(object sender, EventArgs e) // Check that a file is actually being submitted. if (Uploader.PostedFile.FileName == "") lblInfo.Text = "No file specified."; else // Check the extension. string extension = Path.GetExtension(Uploader.PostedFile.FileName);
An example which accepts .bmp, .gif and .jpg extensions switch (extension.ToLower()){ case ".bmp": case ".gif": case ".jpg": break; default: lblInfo.Text = "This file type is not allowed."; return; } // Using this code, the saved file will retain its original // file name when it's placed on the server. string serverFileName = Path.GetFileName( Uploader.PostedFile.FileName); string fullUploadPath = Path.Combine(uploadDirectory, serverFileName); try{ Uploader.PostedFile.SaveAs(fullUploadPath); lblInfo.Text = "File " + serverFileName; lblInfo.Text += " uploaded successfully to"; lblInfo.Text += fullUploadPath; catch (Exception err){ lblInfo.Text = err.Message;}}}}
Additional Notes Dissecting the Code . . . The saved file keeps its original (client-side) name. The code uses the Path.GetFileName() static method to transform the fully qualified name provided by FileUpload.Posted-File.FileName and retrieve just the file, without the path. The FileUpload.PostedFile object contains only a few properties. One interesting property is ContentLength, which returns the size of the file in bytes. You could examine this setting and use it to prevent a user from uploading excessively large files.
Limitations By default, ASP.NET will reject a request that’s larger than 4MB. However, you can alter this maximum by modifying the maxRequestLength setting in the web.config file. This sets the largest allowed file in kilobytes. The web server will refuse to process larger requests. The following sample setting configures the server to accept files up to 8MB: <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <!-- Other settings omitted for clarity. --> <httpRuntime maxRequestLength="8192" /> </system.web> </configuration> Be careful, though. When you allow an 8MB upload, your code won’t run until that full request has been received. This means a malicious server could cripple your server by sending large request messages to your application. Even if your application ultimately rejects these messages, the ASP.NET worker process threads will still be tied up waiting for the requests to complete. This type of attack is called a denial-of-service attack, and the larger your allowed request size is, the more susceptible your website becomes.