1

I have a sub to upload file. How do I restrict the filetype that can be uploaded? I don't want the user to be able to upload .exe, .dll, .ini files. Right now any files can be uploaded.

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If FileUpload1.HasFile Then
        Try
            FileUpload1.SaveAs("C:\Uploads\" & _
                FileUpload1.FileName)
            Label1.Text = "File name: " & _
                FileUpload1.PostedFile.FileName & "<br>" & _
                "File Size: " & _
                FileUpload1.PostedFile.ContentLength & "<br>" & _
                "Content type: " & _
                FileUpload1.PostedFile.ContentType & "<br>" & _
                "Location Saved: C:\Uploads\" & _
                FileUpload1.FileName
        Catch ex As Exception
            Label1.Text = "ERROR: " & ex.Message.ToString()
        End Try
    Else
        Label1.Text = "You have not specified a file."
    End If
End Sub
Dan Lowe
  • 37,115
  • 15
  • 104
  • 98
Ags
  • 13
  • 2
  • possibly duplicate - http://stackoverflow.com/questions/2780191/how-to-restrict-file-type-in-fileupload-control – pedram Jan 07 '16 at 04:24

1 Answers1

0
    If FileUpload1.HasFile Then
      Try
        if FileUpload1.FileName.ToLower().Contains(".exe") or FileUpload1.FileName.ToLower().Contains(".dll")  or FileUpload1.FileName.ToLower().Contains(".ini") 
        ' show your alert here stating this type of files are not allowed
        return
        End if
        FileUpload1.SaveAs("C:\Uploads\" & _
            FileUpload1.FileName)
        Label1.Text = "File name: " & _
            FileUpload1.PostedFile.FileName & "<br>" & _
            "File Size: " & _
            FileUpload1.PostedFile.ContentLength & "<br>" & _
            "Content type: " & _
            FileUpload1.PostedFile.ContentType & "<br>" & _
            "Location Saved: C:\Uploads\" & _
            FileUpload1.FileName
      Catch ex As Exception
            Label1.Text = "ERROR: " & ex.Message.ToString()
      End Try
      Else
            Label1.Text = "You have not specified a file."
      End If

But, I would suggest you client side check will be better too.

Community
  • 1
  • 1
Just code
  • 12,567
  • 10
  • 45
  • 82