With AspUpload, an uploaded file can be saved in an ODBC-enabled database
in just one line of code via the method File.ToDatabase. This method accepts two
arguments: an ODBC connection string, and an INSERT or UPDATE SQL statement
which must contain one question mark sign (?) as a placeholder
for the file being saved in the database, for example:
File.ToDatabase "DSN=mydb;UID=jsmth;PWD=xxx",_
"INSERT INTO IMAGES(img, name) VALUES(?, 'name.ext')"
This statement inserts the current file into the field
img of the table IMAGES, and the string 'name.ext' into the field name.
The DSN parameter in the first argument points to a system DSN creatable
via the ODBC control panel. A DSNless connection string for MS Access
must explicitly reference the full path to the MDB file, as follows:
File.ToDatabase "Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\path\db.mdb", ...
For SQL Server, your connection string may look as follows:
"Driver=SQL Server;Server=MYSERVER;UID=sa;PWD=xxxxxx"
If you need to replace an existing file in a record, you should use an UPDATE
statement instead of INSERT, for example:
"UPDATE MYIMAGES SET img=?, name='newname.ext' WHERE id=3"
The sample files odbc.asp and odbc_upload.asp
demonstrate the use of the ToDatabase method. The form
located in the file odbc.asp (not shown here) contains a file item THEFILE
and a text item DESCR. Here is what odbc_upload.asp looks like:
<HTML>
<BODY>
<%
Set Upload = Server.CreateObject("Persits.Upload")
' Capture files
Upload.Save "c:\upload"
' Obtain file object
Set File = Upload.Files("THEFILE")
If Not File Is Nothing Then
' Build ODBC connection string
Connect = "Driver={Microsoft Access Driver (*.mdb)};DBQ=" & Server.MapPath(".\aspupload.mdb")
' If you use SQL Server, the connecton string must look as follows:
' Connect = "Driver=SQL Server;Server=MYSERVER;UID=sa;PWD=xxxxxxxxx"
' Build SQL INSERT statement
SQL = "INSERT INTO MYIMAGES(image_blob, filename, description, filesize) VALUES(?, '"
SQL = SQL & File.Filename & "', '"
SQL = SQL & Replace(Upload.Form("DESCR"), "'", "''") & "', "
SQL = SQL & File.Size & ")"
' Save to database
File.ToDatabase Connect, SQL
Response.Write "File saved."
Else
Response.Write "File not selected."
End If
%>
</BODY>
</HTML>
|
Note the use of the built-in Replace function which replaces all occurrences
of the ' character (single quote) by two single quotes to avoid
a run-time error if the description contains single quotes.
Click the link below to run this code sample:
http://localhost/aspupload/04_db/odbc.asp
AspUpload also provides the top-level method Upload.ToDatabaseEx
which enables you to save an arbitrary file on your system in the database, not just an uploaded file.
The first argument for this method is a file path, the other two are the same as for
the method File.ToDatabase.