?
Solved

ASP.Net File upload control limit file extensions

Posted on 2009-03-31
10
Medium Priority
?
2,182 Views
Last Modified: 2012-05-06
How can I limit the type of files that are allowed to be uploaded using the code below?
Imports System.IO
Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
 
        Dim con As New System.Data.OleDb.OleDbConnection
        Dim myPath As String
 
 
        myPath = Server.MapPath("App_Data/BestPractices.mdb")
        con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data source=" & myPath & ";"
 
        Dim insCmd As New System.Data.OleDb.OleDbCommand
 
        'insCmd.CommandText = "insert into Data (Import_Export,Location,Descp,Cont,Share_MDY) values('" & ddType.SelectedValue & "','" & Replace(txtLocation.Text, "'", "''") & "','" & Replace(txtDescription.Text, "'", "''") & "','" & Replace(txtContact.Text, "'", "''") & "',#" & StartDatetxt.Text & "#)"
 
        insCmd.CommandText = "insert into Data (Import_Export,Location,Descp,Contact,Share_MDY) " & _
                     " values('" & ddType.SelectedValue & "','" & Replace(txtLocation.Text, "'", "''") & "','" & _
                     Replace(txtDescription.Text, "'", "''") & "','" & Replace(txtContact.Text, "'", "''") & "',#" & _
                     StartDatetxt.Text & "#)"
 
 
 
        insCmd.Connection = con
 
        Dim idCmd As New System.Data.OleDb.OleDbCommand
 
        idCmd.Connection = con
        con.Open()
        insCmd.ExecuteNonQuery()
        con.Close()
 
 
        Dim strStatusMessage As String
 
        Try
            Dim hfc As HttpFileCollection = Request.Files
 
            For i As Integer = 0 To hfc.Count - 1
 
                Dim hpf As HttpPostedFile = hfc(i)
 
 
                If hpf.ContentLength > 0 Then
 
                    If Not File.Exists(Server.MapPath("~/uploads/") & "\" & Path.GetFileName(hpf.FileName)) Then
 
                        hpf.SaveAs(Server.MapPath("~/uploads/") & "\" & Path.GetFileName(hpf.FileName))
                        strStatusMessage = "File saved at: \\cletnsrv01\EBE\Reports_Data_List_Charts\Best Practice Sharing\"
                    Else
                        strStatusMessage = "Diddnt Overwrite"
                    End If
                End If
 
            Next i
 
 
        Catch Ex As Exception
            strStatusMessage = "Unable to save the uploaded file.  " _
             & "The error was: " & Ex.Message
 
        Finally
            lblSaveResults.Visible = True
            lblSaveResults.Text = strStatusMessage
            lblreceive.Visible = True
            tblresults.Visible = True
            lblFileName1.Text = FileUpload1.PostedFile.FileName
            lblFileType1.Text = FileUpload1.PostedFile.ContentType
            lblFileSize1.Text = FileUpload1.PostedFile.ContentLength
 
 
            If FileUpload2.HasFile Then
                lblFileName2.Text = FileUpload1.PostedFile.FileName
                lblFileType2.Text = FileUpload1.PostedFile.ContentType
                lblFileSize2.Text = FileUpload1.PostedFile.ContentLength
            Else
                lblFileName2.Text = ""
                lblFileType2.Text = ""
                lblFileSize2.Text = ""
 
                If FileUpload3.HasFile Then
                    lblFileName3.Text = FileUpload1.PostedFile.FileName
                    lblFileType3.Text = FileUpload1.PostedFile.ContentType
                    lblFileSize3.Text = FileUpload1.PostedFile.ContentLength
                Else
                    lblFileName3.Text = ""
                    lblFileType3.Text = ""
                    lblFileSize3.Text = ""
 
                    If FileUpload4.HasFile Then
                        lblFileName4.Text = FileUpload1.PostedFile.FileName
                        lblFileType4.Text = FileUpload1.PostedFile.ContentType
                        lblFileSize4.Text = FileUpload1.PostedFile.ContentLength
                    Else
                        lblFileName4.Text = ""
                        lblFileType4.Text = ""
                        lblFileSize4.Text = ""
                    End If
                End If
            End If
        End Try

Open in new window

0
Comment
Question by:ITHelper80
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
10 Comments
 
LVL 23

Expert Comment

by:apresto
ID: 24030737
If you want to simply check the extension of a file you can use the FileInfo class of the System.IO namespace.
FileInfo file = new FileInfo("C:\\myfile.asp");
then you can access the extension with the file.Extension attribute of this object. Knowing this you can create an If/Switch statement to carry out an action depending on the extension
0
 
LVL 23

Expert Comment

by:apresto
ID: 24030752
Or, you can just use this:
System.IO.Path.GetExtension(this.hpf.PostedFile.FileName);
0
 
LVL 6

Author Comment

by:ITHelper80
ID: 24031706
Could you offer a snippet of how to use System.IO.Path.GetExtension(this.hpf.PostedFile.FileName);
to prevent someone from uploading say an .exe file?
0
Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

 

Accepted Solution

by:
godirect earned 1100 total points
ID: 24032179
You could throw a ExpressionValidator out there and make sure to validate before running anything.


<asp:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" ErrorMessage="Upload Excel, PDF and ZIP files only." ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.xls|.XLS|.pdf|.PDF|.zip|.ZIP|.Zip)$" ControlToValidate="hpf" Display="None"></asp:RegularExpressionValidator>

Open in new window

0
 
LVL 6

Author Comment

by:ITHelper80
ID: 24033374
Godirect.

Your validation code does work except when I click on the submit button its tries to validate the field again and throw an error. How can I stop that?
0
 
LVL 23

Expert Comment

by:apresto
ID: 24034987
You can set the "CausesValidation" attribute in the button to false, but this means that when you click submit it will not validate any of the form.
<asp:Button runat="server" CausesValidation="false"...
And in response to your previous question, you can use the System.IO Example like this: (but godirect's is a better solution)

   If System.IO.Path.GetExtension(this.hpf.PostedFile.FileName).ToLower() = "exe" Then
      //This file is invalid, do something
   Else
      //This IS a valid file, do something else
   End If

Open in new window

0
 
LVL 6

Author Comment

by:ITHelper80
ID: 24035024
Thanks apresto but my problem I am doing validation of other fields so I cant disable that attribute.
0
 
LVL 23

Assisted Solution

by:apresto
apresto earned 900 total points
ID: 24035036
Ok, well add the attributes that you want to have the button validate to a validation group, then add the button itself to a validation group and this should solve your problem.
Add this to the Validation Controls and the Button that fires the validation:
...runat="server" ValidationGroup="MyValGroup" Id=".....
0
 
LVL 6

Author Comment

by:ITHelper80
ID: 24038445
Thanks that took care of it. Since both apresto and godirect help me solve this problem I am going to split the points. Thanks to you both.
0
 
LVL 23

Expert Comment

by:apresto
ID: 24038992
No problem, glad we could help
Apresto
0

Featured Post

What is a Denial of Service (DoS)?

A DoS is a malicious attempt to prevent the normal operation of a computer system. You may frequently see the terms 'DDoS' (Distributed Denial of Service) and 'DoS' used interchangeably, but there are some subtle differences.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question