In the btnUpload_Click() event of "btnUpload" we
have to add the following code, which will check the maximum size of the file
and also filter the extension.
Listing 4: Server side filter action
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles btnUpload.Click
Try
Dim intDocFileLength As Integer = Me.fileDocument.PostedFile.ContentLength
Dim strPostedFileName As String = Me.fileDocument.PostedFile.FileName
If intDocFileLength > 4096000 Then '4MB
Me.lblUploadErr.Text = "Image file size exceeds the limit of 4000 kb."
Exit Sub
End If
If (strPostedFileName <> String.Empty) Then
Dim strExtn As String = System.IO.Path.GetExtension(strPostedFileName).ToLower
If (strExtn = ".txt") Or (strExtn = ".doc") Or (strExtn = ".rtf") Or _
(strExtn = ".pdf") Or (strExtn = ".sxw") Or (strExtn = ".odt") Or _
(strExtn = ".html") Or (strExtn = ".stw") Or (strExtn = ".htm") Or _
(strExtn = ".sdw") Or (strExtn = ".vor") Then
Dim savePath As String = _
Server.MapPath(ConfigurationManager.AppSettings("UploadedPath")) & "\"
Me.fileDocument.PostedFile.SaveAs(savePath & _
System.IO.Path.GetFileName(strPostedFileName))
Me.lblUploadErr.Text = "Document uploaded successfully..."
Else
Me.lblUploadErr.Text = _
"Please upload a valid Document with the extenion in : <br>"
Me.lblUploadErr.Text + = _
".txt, .doc, .rtf, .pdf, .sxw, .odt, .stw, .html, .htm, .sdw Or .vor"
End If
Else
Me.lblUploadErr.Text = "There is no file to Upload."
End If
Catch ex As Exception
'TODO: Add the Error log entry logic!
End Try
End Sub
Let us move through the codes. The
fileDocument.PostedFile.ContentLength property of FileUpload control will give
the size of the posted file as bytes and the fileDocument.PostedFile.FileName
property will give the file name of the posted one. Then we check for the
maximum size which is fixed to 4 MB as 4096000 bytes here. Then we get the file
extension using the System.IO.Path.GetExtension() method of the input file. We
match the posted extension with our given extensions. If the match satisfies,
we do the Uploading action or else we show the error message in label.