Restricting File Types
There are times when you may need to restrict the type of files uploaded from a client's machine.
You can do so by using the ContentType property of SA-FileUp and a Select condition to save only files
that are a certain type.
Once your file is uploaded, you would include the following line after you have created an instance
of SA-FileUp:
<%
....
'--- Parses out the file name
'---
FName = Mid(upl.UserFilename, InstrRev(upl.UserFilename, "\") + 1)
'--- This line parses out the Content type.
'---
FCONT = upl.ContentType
'--- This would equal to
'--- "image/pjpeg"
'--- "image/gif"
'--- "text/plain", etc.
'--- You can then use the Select Case Condition to restrict the file type.
Select Case LCase(FCONT)
Case "image/gif"
upl.Save
Response.Write "<P>" & FName & " has been saved."
Case "image/pjpeg"
upl.Save
Response.Write "<P>" & FName & " has been saved."
Case Else
upl.delete
Response.Write "<P>" & "You are restricted to only upload gif and Jpeg files.<BR>"
Response.End
End Select
....
%>
Let go though the code:
- First we parse out the filename using two handy methods - Mid() and InstrRev().
The combination of these methods and the UserFilename property should get us just
the name of the file, not the full path. The variable Fname is used within the response of the Case condition
statement.
- We get the media content type of the file uploaded by using the ContentType property.
In this example, we restrict all file except Gif and Jpeg files. So we are looking for
either "image/pjpeg" or "image/gif" as the media content type.
- A Case condition statement is used to save the correct file and send a successful response.
Notice that the variable FName is used to supply the file that was saved. If the file type is
incorrect, the file will be deleted and a error response will given.
What did we learn?
Now you can restrict file types with ease.
- To identify a file's name, use the Mid() and InstrRev() methods with the UserFilename property.
- To restrict a file by media type, identify the media content of an uploaded file using the ContentType
property.
- To acknowledge the sucessful completion of the file restriction, use a Case condition statement.
That completes the Basics tutorial. You can also try the other tutorials: