A Simple ASP File Upload Application
This tutorial will show
you the steps needed to build a simple application to enable
users to upload PDF files to the server, delete existing files
and view the files in thier browser. This example uses our
own dgFileUpload component and you can download a 15
day trial version here
so you can follow the tutorial and test the finished application
on your own server. All the source code, along with the small
Access 2000 database used in this tutorial, can be downloaded
as a ZIP archive here.
After downloading
and un-zipping the archive, create a new directory under your
web root (e.g. 'c:\inetpub\wwwroot\dgUpload') and put the
two ASP pages ('upload.asp' and 'display.asp') and the database
in there. You will also have to create a directory called
'pdfs' and set the security on this directory to allow full
control for the 'Internet Guest Account' user. To do this,
right-click on the 'pdfs' folder and select 'Properties' and
then the 'Security' tab. If 'Internet Guest Account' is not
already listed, click the "Add' button and then select
the machine name from the 'Look in' drop-down menu. Scroll
down until you see 'IUSR_[machinename]', select this user
and click the 'Add' button. Hit 'Ok' to get back to the 'Properties'
window, select the newly added user and give this entry 'Full
Control'. You will now be able to test the application by
entering the following URL into a browser:
http://localhost/dgUpload/upload.asp
On this page you will
see two input fields; the first allows you to select the PDF
file you want to upload and the other lets you enter a display
name for the file. This name will be shown as a link to view
the file on 'display.asp' after uploading. Browse to a suitable
PDF file, enter a name and then click the 'Upload' button.
Your file will be uploaded to and you will be redirected to
the display page which will have a link to the file. The details
(path, display name and date uploaded) of each file are stored
in the database. Let's look at the code that does this.
After declaring our
variables, the first thing we do is open a connection to the
database.
Set
cnnDB = Server.CreateObject("ADODB.Connection")
strConn = "DRIVER={Microsoft Access Driver (*.mdb)};"
& _
"DBQ="
& Server.MapPath("newsletters.mdb")
cnnDB.Open strConn
Then we need to create
an instance of the file upload component (in this case, dgFileUpload).
Set
oPost = Server.CreateObject("dgFileUpload.dgUpload")
Because we want to restrict the file size of the uploaded
PDFs to something reasonable we will set this to 10 Megabytes.
oPost.MaxFileSize = 10000000
Next we grab the data posted from the form by calling the
'GetPostData' method.
oPost.GetPostData()
The following code grabs the filename and the display name
from the form collection, builds and executes the SQL query
to store the file details in the database and then saves the
file to the specified directory on the server. View the source
of 'upload.asp' to see how this code integrates with the rest
of the application.
' get the filename and display name
strDisplayName = oPost.Form("displayText")
strFileName = oPost.Files("pdfFile").FileName
' build the INSERT query
strQuery = "INSERT INTO NewsLetters (Filename, DisplayName)
VALUES ('" & strFilename & "', '"
& strDisplayName & "')"
cnnDB.Execute(strQuery)
' get the folder where we want to store the
pdf
strFolder = Server.MapPath("pdfs") & "\"
' save the uploaded pdf to the specified directory
intResult = oPost.Files("pdfFile").Save(strFolder
& strFileName, 1)
' if the file upload is successful, redirect to
' the page that displays the files ("display.asp")
If intResult = 0 Then
cnnDB.Close
Set cnnDB = Nothing
Response.Redirect("display.asp")
Else
strFeedBack = "File upload
failed. Error #" & intResult
End If
If there is a problem with the upload or save process the
'strFeedback' variable is assigned a suitable message that
is then displayed to the user. This is handled using client-side
JavaScript once the page has been processed. Again, see the
supplied source code for more details of how this works.
As mentioned before, the above example uses dgFileUpload
but the process is similar whichever file upload component
you use. The rest of this tutorial is extracted from an article
on file upload components written by Michael Allen Smith and
describes the process of uploading files using two other components,
Software Artisans FileUp and Persists AspUpload.
Both (FileUp and AspUpload) handle uploads slightly differently.
Let's code each of these components to handle our requirements
(upload only image files below a specified size).
The form, where the client uploads a file, is identical for
both.
<form name="form" action="upload.asp"
enctype="MULTIPART/FORM-DATA" method="POST">
<input type="file" name="file1">
<input type="submit" value="Upload Files">
</form>
Before you pick which component you will be using, here is
some common code that both can use. isFileSizeOK handles the
file size restrictions. isValidFile is where you'll define
what file extensions the client can upload.
<%
intMaxFileSize = 8000
strUploadFolder = "c:\uploadFolder"
Function isFileSizeOK(bytes)
' restrict file byte size
byteMAX = intMaxFileSize
If bytes > byteMAX Then
isFileSizeOK = FALSE
Else
isFileSizeOK = TRUE
End If
End Function
Function isValidFile(filename)
' define what file types you will permit to upload
fileExtension = lcase(right(filename,4))
select case fileExtension
case ".gif",".jpg",".png","jpeg"
isValidFile = TRUE
case else
isValidFile = FALSE
end select
End Function
%>
Now the code for Software Artisans FileUp.
<%
Sub uploadSA
Set up = Server.CreateObject("SoftArtisans.FileUp")
up.Path = uploadFolder
If NOT up.IsEmpty Then
filename = Mid(up.UserFilename, InstrRev(up.UserFilename,
"\") + 1)
' restrict file types to upload
If isValidFile(filename) Then
' restrict file by size
If isFileSizeOK(up.TotalBytes) Then
up.Save
strUploadStatus1 = "File ["
& filename & "] Uploaded Successfully! "
& up.TotalBytes
Else
strUploadStatus1 = "ERROR:
File Too Large: " & filename & " ("
& up.TotalBytes & "
bytes)"
End If
Else
strUploadStatus1 = "ERROR: This File Type
is restricted from uploading: " & filename
End If
End If
Set up = Nothing
End Sub
%>
With Persist's AspUpload, you save the file first, then perform
checks. If the file fails the checks, then the code deletes
it from the server. This component also has a "SaveToMemory"
option, which bypasses the write to the disk until instructed.
ASPUpload has built-in image size handling and can detect
if a file is an image with the .ImageType property, but for
this example we'll use the isValidFile function.
<%
Sub uploadPersists
Set up = Server.CreateObject("Persits.Upload.1")
up.OverwriteFiles = TRUE
up.SetMaxSize intMaxFileSize
up.Save uploadFolder
For Each File in up.Files
fileName = File.ExtractFileName
If isValidFile(fileName) Then
If isFileSizeOK(File.OriginalSize)
Then
strUploadStatus2 = "File ["
& filename & "] Uploaded Successfully! "
Else
strUploadStatus2 = "ERROR:
File Too Large: " & fileName & " ("
& File.OriginalSize & "
bytes)"
File.Delete
End If
Else
File.Delete
strUploadStatus2 = "ERROR: This File Type
is restricted from uploading: " & fileName
End If
Next
End Sub
%>
Michael Allen Smith is a web developer living in San Diego.
In addition to his web development site Digital Colony, he
also runs INeedCoffee.com, a non-commercial site devoted to
coffee.
|