Persits Software, Inc. Knowledge Base Articles

HOWTO: Uploading certain file types only

Problem Description

AspUpload does not offer a property for allowing only certain file types (extensions) to be uploaded. However, this functionality can be easily implemented by script.

Solution

The following code snippets demonstrate two different approaches to limiting the acceptable file types to .DOC and .TXT only. You can easily customize these code samples to work with any other file types.

Method 1: Upload to disk, then delete unwanted files

<%
Set Upload = Server.CreateObject("Persits.Upload")
Upload.Save "c:\upload"

For Each File in Upload.Files
   Ext = UCase(Right(File.Path, 3))
   If Ext <> "TXT" and Ext <> "DOC" Then
      Response.Write "File " & File.Path & " is of invalid type."
      File.Delete
   End If
Next
%>

Method 2: Upload to memory, then only save valid files to disk

<%
Set Upload = Server.CreateObject("Persits.Upload")
Upload.SaveToMemory

For Each File in Upload.Files
   Ext = UCase(Right(File.Path, 3))
   If Ext <> "TXT" and Ext <> "DOC" Then
      Response.Write "File " & File.Path & " is of invalid type."
   Else
      File.SaveAs "c:\upload\" & File.ExtractFileName
   End If
Next
%>

If you need to check whether an uploaded file is an image, you may use the property File.ImageType instead of examining the file extension.