Emerald Emerald - 1 month ago 8
Vb.net Question

File filtering (ASP.Net, VB.Net)

I am making a filtering on files selected by user. Here is my coding that I currently use for button upload click event.

Dim validFileTypes As String() = {"jpg", "JPG", "jpeg", "JPEG", "png", "PNG"}
Dim ext As String = Path.GetExtension(fileUpload.PostedFile.FileName)
Dim isValidFile As Boolean = False

If fileUpload.HasFile Then
For i As Integer = 0 To validFileTypes.Length - 1
If ext = "." & validFileTypes(i) Then 'if selected url got extension like listed above
isValidFile = True 'file is valid
Dim hfc As HttpFileCollection = Request.Files
For j As Integer = 0 To hfc.Count - 1
Dim hpf As HttpPostedFile = hfc(j)
If hpf.ContentLength > 0 Then
hpf.SaveAs(Server.MapPath("source") & "\" & Path.GetFileName(hpf.FileName))
End If
Next
Else
Alert("Failed to upload! Please select file with valid extension.")
End If
Next
Else
Alert("Please select image!")
End If


So if user select file with wrong extension, file will not be uploaded into temporary file. Since the
validFileTypes
consist of 6 types so the
Alert("Failed to upload! Please select file with valid extension.")
will appear 6 times even though the file selected is only 1. I tried to fix it but need some guidance from you guys. Thank you.

Answer

I have made some improvements on your code and fixed some of the downsides for you.

Dim validExtensions As String() = {"jpg", "JPG", "jpeg", "JPEG", "png", "PNG"}

' Check if request has no file
If Request.Files.Count = 0 Then
    Alert("Please select image!")
Else
    'Otherwise get files from request
    Dim files As HttpFileCollection = Request.Files
    'Loop through file names
    For Each fileName as String In files.AllKeys
        'Get file from posted files
        Dim file As HttpPostedFile = files(fileName)
        'Check content length of file
        If file.ContentLength > 0 Then
            'Get file extension of file
            Dim extension As String = Path.GetExtension(file.FileName)
            'Check if file extension is valid
            If validFileTypes.Contains(extension) Then
                'Save file
                file.SaveAs(Server.MapPath("source") & "\" & Path.GetFileName(file.FileName))
            Else
                Alert("Failed to upload! Please select file with valid extension.")
                Exit For 'Break loop
            End If
        End If
    Next
End If