programming4us
programming4us
WEBSITE

ASP.NET 4 in VB 2010 : Files and Streams - Allowing File Uploads

- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019

Although you've seen detailed examples of how to work with files and directories on the web server, you haven't yet considered the question of how to allow file uploads. The problem with file uploading is that you need some way to retrieve information from the client—and as you already know, all ASP.NET code executes on the server.

1. The FileUpload 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 events you can use through the control tag:

<asp:FileUpload ID="Uploader" runat="server" />

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 hardwired 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")

Figure 1 shows a complete web page that demonstrates how to upload a user-specified file. This example introduces a twist—it allows the upload of only those files with the extensions .bmp, .gif, and .jpg.

Figure 1. A simple file uploader

Here's the code for the upload page:

Public Partial Class UploadFile
    Inherits System.Web.UI.Page

    Private uploadDirectory As String

    Protected Sub Page_Load(ByVal sender As Object, _
      ByVal e As EventArgs)  Handles Me.Load

        ' Place files in a website subfolder named Uploads.
        uploadDirectory = Path.Combine( _
          Request.PhysicalApplicationPath, "Uploads")
    End Sub

Protected Sub cmdUpload_Click(ByVal sender As Object, _
      ByVal e As System.EventArgs) Handles cmdUpload.Click

        ' Check that a file is actually being submitted.
        If Uploader.PostedFile.FileName = "" Then
            lblInfo.Text = "No file specified."
        Else
            ' Check the extension.
            Dim extension As String = _
              Path.GetExtension(Uploader.PostedFile.FileName)

            Select Case extension.ToLower()
                Case ".bmp", ".gif", ".jpg"
                    ' This is an allowed file type.
                Case Else
                    lblInfo.Text = "This file type is not allowed."
                    Return
            End Select

            ' Using this code, the saved file will retain its original
            ' file name when it's placed on the server.
            Dim serverFileName As String = _
              Path.GetFileName(Uploader.PostedFile.FileName)
            Dim fullUploadPath As String = _
              Path.Combine(uploadDirectory, serverFileName)

            Try
                Uploader.PostedFile.SaveAs(fullUploadPath)

                lblInfo.Text = "File " & serverFileName
                lblInfo.Text &= " uploaded successfully to "
                lblInfo.Text &= fullUploadPath
            Catch Err As Exception
                lblInfo.Text = err.Message
            End Try
        End If

    End Sub

End Class

					  

1.1. Dissecting the Code . . .
  • The saved file keeps its original (client-side) name. The code uses the Path.GetFileName() shared method to transform the fully qualified name provided by FileUpload.PostedFile.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.

THE MAXIMUM SIZE OF A FILE UPLOAD

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.
Other  
 
Top 10
Free Mobile And Desktop Apps For Accessing Restricted Websites
MASERATI QUATTROPORTE; DIESEL : Lure of Italian limos
TOYOTA CAMRY 2; 2.5 : Camry now more comely
KIA SORENTO 2.2CRDi : Fuel-sipping slugger
How To Setup, Password Protect & Encrypt Wireless Internet Connection
Emulate And Run iPad Apps On Windows, Mac OS X & Linux With iPadian
Backup & Restore Game Progress From Any Game With SaveGameProgress
Generate A Facebook Timeline Cover Using A Free App
New App for Women ‘Remix’ Offers Fashion Advice & Style Tips
SG50 Ferrari F12berlinetta : Prancing Horse for Lion City's 50th
- Messages forwarded by Outlook rule go nowhere
- Create and Deploy Windows 7 Image
- How do I check to see if my exchange 2003 is an open relay? (not using a open relay tester tool online, but on the console)
- Creating and using an unencrypted cookie in ASP.NET
- Directories
- Poor Performance on Sharepoint 2010 Server
- SBS 2008 ~ The e-mail alias already exists...
- Public to Private IP - DNS Changes
- Send Email from Winform application
- How to create a .mdb file from ms sql server database.......
programming4us programming4us
programming4us
 
 
programming4us