ASP.Net - Simple File Upload

Asp.Net makes uploading files as simple as a few lines of code. In this article, I explain how to upload files using Web Forms and C#.
Let's being with a simple empty website project. Once the project is loaded, you'll need to add a default Web Form. Be sure to click the "Place code in separate file" option when adding the form. Once the form has been added, open the template file and add the following code in the form tag.
  1. <asp:FileUpload ID="file" runat="server" />  
  2. <asp:Button ID="upload" Text="Upload" runat="server" OnClick="FileUpload" /> 
The FileUpload control, will render a file input element onto the page and the Button control will trigger the file upload event. Notice, a click event handler has been added to the button. In your code behind file, you'll need to create this event handler. Open the Default.cs file and add the following event method.
  1. protected void FileUpload(object sender, EventArgs e)  
  2. {  
  3.  
  4. } 
The FileUpload control exposes various properties and methods that you can use to inspect an uploaded file. Let's start by getting the file name.
  1. string fileName = file.FileName;  
  2. Response.Write(fileName)
In the code above, the variable file is the ID given to the FileUpload control. The PostedFile property will give you more details about the file such as ContentType and ContentLength. Before you begin processing a file, it's worth checking if a file has been uploaded. You can use the HasFile property to check if a file has been posted.
  1. if (file.HasFile)  
  2. {  
  3.     Response.Write(file.FileName);  
  4. }else{  
  5.     Response.Write("No file uploaded");  
  6. } 
Once, the file has been uploaded, you can save it on the server using the SaveAs method. This method accepts a single argument filename, which is configured to require a rooted path.
  1. if (file.HasFile)  
  2. {  
  3.     file.SaveAs(Server.MapPath("~/" + file.FileName));  
  4. }else{  
  5.     Response.Write("No file uploaded");  
  6. } 
In some situations, you might want to process the file without saving it on the server immediately. For example, you might want to upload an image and resize it before saving it. In such situations, you can use the FileBytes property to get an array of bytes in the posted file or the FileContent property to get a stream of the posted file. The code below shows how to use the FileContent property to check if a posted file is an Image.
  1. if (file.HasFile)  
  2. {  
  3.     try  
  4.     {  
  5.          System.Drawing.Image img = System.Drawing.Image.FromStream(file.FileContent);  
  6.          // Process image  
  7.     }  
  8.     catch  
  9.     {  
  10.          Response.Write("Posted file is not an image");  
  11.     }  
  12. }else{  
  13.     Response.Write("No file uploaded");  
  14. } 

No comments:

Post a Comment