Categories

 

 

 

Valid XHTML 1.0 Transitional

 

Valid CSS!

 

Tutorials > Adobe Dreamweaver > Tutorial #168

Uploading Files

Level: Intermediate
Requirements: DreamweaverMX, Access2000
Language: ASP VBScript

Introduction

For this tutorial you will need to be very comfortable with the editing of code within Dreamweaver. You will also need a copy of the selected uploading component used in this tutorial from Lite Software:

http://www.igra.ws/Product/ASP/Reuse/Uploader/Default.htm

As this link is currently unavailable in its previous format, you can download the entire zip file of the component from WebThang, to download the component in its entirity click on this link.

In this tutorial we are firstly going to create a page that will allow the user to upload any selected type of file and save the details of this to the database. We will then delve further into this and provide a page that allows for image uploads only but also gets some extra details about the image and saves that to the database.

Please note: to highlight where to insert code properly, all code that is highlighted in yellow means that this code is to be copied to your page. Any code that is not highlighted in yellow is simply there as an indicator of where to place the highlighted code.

SECTION 1: UPLOADING ANY FILE.

For the first part of this tutorial, we will create a page that will allow a user to upload any type of file.

Step 1: Creating the table.

As we are simply going to upload one file to the host server, all we will need is the one table.

tblUploadedFiles
- FileID (PK, AN)
- Filename (Text, Size=100)
- Description (Text, Size=100)

Step 2: Creating the form.

Very basically, all we will require from the user is the location of the file they wish to upload, add a bit of detail about it then upload it. So to do this we will need a form that captures this information.

Create a new page called fileUpload.asp and on it create a form with a file field, a text field, a hidden field and a submit button, naming them as shown below.

image001

image002

Save the page and open the code editor.

With the basic form now done, it is time to create the actual code that will do the bulk of the work for us.

Step 3: Uploading the file.

Create a new file and called it uploadThisFile.asp, and open the file. First things first, we need to include the Upload.asp component to this directory. If you have not unzipped the package, then do so and copy and paste the Upload.asp file from it to the same folder where you have created the fileUpload.asp page.

Create the following line underneath the language declaration at the top of the page.

<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<!--#include file="Upload.asp" -->

The following lines of code initiate the upload component and prepare the page to upload the file. Copy this code under the previous include line. Remember, text in blue should be entered as one full line of code.

<%
'Upload the image file and get reference to component
Dim Uploader, File
Set Uploader = GetASPUploader

'Use AddFile method to add file objects and change their properties as needed
Set File = Uploader.AddFile("file")

The last line of code gets the filename of the file entered on the previous page by the user. If you change the name of the file field on the first page, you must ensure that this is changed to equal it.

The following code sets up the restrictions to which the uploaded file has to adhere to. The ValidFileTypes does exactly what it says on the tin. In here you simply add what file types you are going to allow to be uploaded. If you want a free for all, simply omit this line entirely. The MaxSize field is measured in bytes. So we will set this initially to 1mb by entering 1024x1024. The File.Overwrite tells the page to either overwrite the file or not if a file of the same name is found on the server.

'The the properties of the upload
File.ValidFileTypes = "doc,pdf,txt,xls,mdb,jpg,gif,bmp,png"
File.MaxSize = 1024*1024
File.Overwrite = false 'Do not overwrite, create unique filename

We now need to set the folder to which the file is to be uploaded to. Because the script is run from the server, this location MUST point to the physical path of the folder in which to save the uploaded files.

'Set the folder name to where the file will be uploaded to
Uploader.Destination = "C:\TestArea\imageUpload\files\"

We can set the timeout for the script if larger files are to be expected. We can then initiate the upload whilst checking for any errors that do occur.

'Set longer timeout for large files if needed
Server.ScriptTimeout = 900

'Enable error handling to catch and handle errors during upload. For example, if user
'  cancels the upload or attempts to upload files of invalid (unallowed) type or size,
'  ASPUploader will raise an exception (error) with relevant description
On Error Resume Next

'Start receiving and saving file(s):
Uploader.Upload

'Check for errors:
If Err Then
  'Redirect with error message
  Response.Write err.description
  Response.End()
End If

'Finally, void the object
Set Uploader=Nothing %>

If no errors occur then the file will have been successfully uploaded. So save the page and open the fileUpload.asp in your browser and give it a go.

The most common error that may occur is that the folder you have set up to hold the uploaded files has not got any write permissions set up for it. If this happens, ensure that the folder in question is set up to allow for this.

Step 4: Saving the file details to the table.

Now that the file has been uploaded, we want to save the details of the newly uploaded file to the table so we can reference it for future use.

So let us create a command from the data bindings panel using the following SQL and variables.

image003

No doubt Dreamweaver will place this new code right at the very top of the page, which is exactly where we do not want it. So a quick copy and paste is required to move that from the top to just before the last line of code we created. Which should look like this...

'Add the details of the uploaded file to the database
Dim myFile, myDescrition
myFile=File.Name
myDescription=Uploader.Form("description")

set cAddDetail = Server.CreateObject("ADODB.Command")
cAddDetail.ActiveConnection = MM_TestDatabase2_STRING
cAddDetail.CommandText = "INSERT INTO tblUploadedFiles ( filename, description ) VALUES
  ( '" & myFile & "', '" & myDescription & "' ) "
cAddDetail.CommandType = 1
cAddDetail.CommandTimeout = 0
cAddDetail.Prepared = true
cAddDetail.Execute()

'Finally, void the object
Set Uploader=Nothing %>

As you will no doubt notice again, the SQL is somewhat incomplete. We did not add any values in the command editor, so we will have to add them here.

Have a quick look back at the fileUpload.asp page and notice the enctype="multipart/form-data" code that sits nicely in the form tag. This tells the page to package the data into separate sections. Sound strange? Well it should, without setting the form like this we would not be able to reference the filename by the component when submitted.

Anyway, back to this page now. Because this page has instantiated the upload component and in turn used this to get the details of the file, we can use this to get the values of the field objects from the previous page.

So without anymore tech talk, we will change the cAddDetail.CommandText line to read as follows...

cAddDetail.CommandText = "INSERT INTO tblUploadedFiles ( filename, description ) VALUES
  ( '" & File.Name & "', '" & Uploader.Form("description") & "' ) "

Save the page and give it a try and check the table once the file has been uploaded. A quick and easy way to get the basic information about the file once it has been uploaded.

SECTION 2: UPLOADING AN IMAGE AND SAVING THE IMAGE DETAILS.

In the second part of this tutorial we only allow the user to upload and image, once done, we will also grab some of the properties of the image, mainly, the width and height of it and save this to the database. Because most of the code can be copied and pasted from the previous sections code, this will be a quick and easy section to complete.

Step 1: Creating the table.

This time round, we will need to have the same kind of table but with a few more fields in it to allow for the extra details to be stored.

tblUploadedImages
- ImageID (PK, AN)
- Filename (Text, Size=100)
- Description (Text, Size=100)
- Width (Number, Field Size=Single)
- Height (Number, Field Size =Single)

Step 2: Creating the form.

To cut a long story short, we will simply copy and paste the fileUpload.asp page from the previous section and rename it imageUpload.asp

We will then change the action of the form to point to a new page we will create called uploadThisImage.asp

image004

Step 3: Getting the image details.

As mentioned before there, most of the work has already been done from the previous sections coding. We simply need to edit a bit here and there and add a few more little things.

So to start us off butchering our code, the first bit we need to change is the ValidTypes. Because we are only going to be accepting image files, we need to tell the script this via this line. So change this to only allow jpg, gif, bmp

File.ValidFileTypes = "jpg,gif,bmp"

Fabulous. Now, because we are going to be adding two extra pieces of data to the table, we need somewhere to store them. So scroll down a touch to this line...

Dim myFile, myDescrition

...and add two new variables called myWidth and myHeight. All we need to do now is place the values of the width and height from the image into these variables and save them to the table.

To do this, we need to employ an extra piece of code that can be nicely wrapped up inside a sub routine. Copy and paste the highlighted code just before the end of your code block.

Sub sImageProperties(vImage)
  Dim image, fs
  Set fs=CreateObject("Scripting.FileSystemObject")
  If Not fs.fileExists(vImage) Then Exit Sub
  Set image = loadpicture(vImage)
  myWidth = Round(image.width / 26.4583)
  myHeight = Round(image.height / 26.4583)
  Set image = Nothing
  Set fs=Nothing
End Sub
%>

The vImage parameter holds the full location and the name of the file. We then create some variables to hold the information about the image. Next we create a FileSystemObject and assign that as the value of fs. We then check to see if the file resides on the server. If not, it will quit the routine and break the insert. We then load the image and assign this to the image variable. From here, we simply gather some details about this file via the properties of the image variable. Once that is all done we void both the image and fs variables.

All that is left to do is to simply call this sub whilst passing through the full path and name of the uploaded file. So scroll up a bit to where declared the my... variables and add the following highlighted line.

myFile=File.Name
myDescription=Uploader.Form("description")
Call sImageProperties(Uploader.Destination & myFile)

Finally, we just need to alter the SQL in the commandText to place the details and the new bits of data into the new table. Alter that line to read like this.

cAddDetail.CommandText = "INSERT INTO tblUploadedImages ( filename, description, width, height ) VALUES ( '" & myFile & "', '" & myDescription & "', " & myWidth & ", " & myHeight & " ) "

With that done, save the file and load the imageUpload.asp file into your browser and give it a try.

You may experience problems with the SQL depending on what type of image file you are trying to upload. The three mentioned above are the most common image files around, however there are more. Some of these however will not work properly with this script. If you wish to check these, enter this final piece of code just before the voiding of the object.

If err<>0 Then Response.Write("Insert error: "& err.description & "<br>SQL= " &
  cAddDetail.CommandText)
'Finally, void the object
Set Uploader=Nothing

It is advisable though if you do use this line to only use it in development and to ensure it is omitted from any page that is used on a live web environment.

This script provides you with a few opportunities to further develop it to make it even more controllable. A few examples of how this can be built on within an admin setup to provide more control over the uploading ability of the user.

1. Building the list of the valid file types dynamically, eg. only allow certain users to upload certain types of file.
2. Dynamically setting the maximum file size for uploaded files.
3. Setting the destination folder from a value on a database to ease administration of a site.

As I said, just a few examples, those above are just some of the things that have been done using this script. Below are a few screenshots of this type of functionality.

Good luck.

#1

image005

#2

image006

#3

image007

Tutorial By Submitted On Views Rating
Rob Boyle 14/02/2007 5415 5 [1 Ratings]
Rate Tutorial