Implement file uploads in a browser with two lines of code

Source: Internet
Author: User
Tags end error code execution file size file upload sql server sql string
Brief introduction
File uploads are the process of sending arbitrary files from the client to the server. The simplest and easiest way to upload is to use browsers that support RFC1867, such as Microsoft's Internet Explorer4.0 version, Netscape3.0 above, or Internet Explorer3.0 with attachments. browser-based file uploads are implemented through HTML form with attributes Enctype= "Multipart/form-data". This form must also contain one or more <input type=file> items to allow the user to specify the local files to be uploaded.


The data sent by a form with the enctype= "Multipart/form-data" attribute must be parsed by a server-side procedure to expand the uploaded files and other non-file entries. In an ASP environment, this task is best accomplished with a compiled Active server component, such as the Persits software company's AspUpload
(http://www.persits.com).

All of the examples in this article are based on the AspUpload installed in your system. You can aspupload down here.
Free Evaluation Edition http://www.persits.com/aspupload.html. After the file is extracted, the AspUpload.dll
Put in any directory, execute command in MS DOS window

regsvr32 c:\dir\AspUpload.dll
Begin
Let's create a simple HTML form that can upload 3 files, and control the upload script.
This is the first HTML file
Test1.htm:
<HTML>
<body bgcolor= "#FFFFFF" >

<form method= "POST" enctype= "Multipart/form-data" action= "uploadscript1.asp" >
<input type=file size=60 name= "FILE1" ><BR>
<input type=file size=60 name= "FILE2" ><BR>
<input type=file size=60 name= "FILE3" ><BR>
<input type=submit value= "upload!" >
</FORM>
</BODY>
</HTML>
Each <input type=file> item is displayed in the browser as a text entry box with a "Browse ..." button. If you do not see the browse button, it is likely that your browser does not support file uploads.

Here is the corresponding upload script uploadscript1.asp:
<HTML>
<BODY>
<%
Set Upload = Server.CreateObject ("Persits.upload.1")
Count = Upload.Save ("c:\upload")
%>
<% = Count%> files uploaded.
</BODY>
</HTML>




The first line of the ASP script only creates an instance of the AspUpload object. The second line invokes the Save method of the component, which actually works by parsing what is sent from the browser, calculating how many files are being uploaded, and putting them in the directory specified on the server. The directory name may or may not end with a backslash. All files will be stored in their original name in the directory. We will soon see how to change the name of any or all of the files.

The Save method returns the number of files that were successfully uploaded. In the event of an error, this method will be discarded.

Note that you can use any or all of the three input boxes in our form. AspUpload has enough intelligence to determine which input boxes are used and which are not.


Use the files and Forms collection to access a single form item
Let's look at the second set of examples:

Test2.htm
<HTML>
<body bgcolor= "#FFFFFF" >

<form method= "POST" enctype= "Multipart/form-data" action= "uploadscript2.asp" >
File 1:<input type=file name= "FILE1" >
Description 1:<input type=text name= "DESCR1" ><BR>
File 2:<input type=file name= "FILE2" >
Description 2:<input type=text name= "DESCR2" ><BR>

<input type=submit value= "upload!" >

</FORM>
</BODY>
</HTML>

Uploadscript2.asp <HTML>
<BODY>
<%
Set Upload = Server.CreateObject ("Persits.upload.1")
Upload.Save "C:\Upload"
%>
Files:<br>
<%
For each File in Upload.files
Response.Write File.name & "= & File.path &" ("& File.size &") <BR> "
Next
%>
<P>
Other items:<br>
<%
For each Item in Upload.form
Response.Write Item.name & "=" & Item.value & "<BR>"
Next
%>
</BODY>
</HTML>



Notice that our HTML form now has two types of input boxes, type=file and Type=text. Because of the Enctype property of our form, we can no longer access the form variable through the standard ASP Response.form collection. Here upload.form to solve the problem. This set is actually the same as Response.form, that is, we can access its elements through shaping or string indexing. For example:

Set Item1 = Upload.form ("DESCR1")

Or

Set Item1 = upload.form (1).

We can also use the For-each statement shown in the example code above to traverse the items in the collection. The Form collection contains an object of type Formitem, which has only two string properties, Name, and Value (the default property).

It is important to remember that the Upload.form collection contains only non-file items, which is different from <input Type=file&gt. AspUpload provides another set, called files, to contain uploadedfile types of objects that represent files that have been uploaded from the <input type=file>. Like a form collection, items in the Files collection can be accessed by using strings or shaping indexes, or a For-each statement, as shown in the previous example.

After running example 2, we'll see something like this:

Files:
File1=c:\upload\file1.xls (108544)
File2=c:\upload\file2.zip (211687)

Other Items:
Descr1=bla bla
Descr2=test Test

Note that we have obtained the destination path and file size of the uploaded file by the UploadedFile object's corresponding path and size attribute.

If our form contains only one file input box, <input type=file name= "Onlyfile", then it is not necessary to use the For-each statement. That's all we need to say.

Response.Write Upload.files ("Onlyfile"). Path

Or, more commonly used

Response.Write Upload.files (1). Path


Important: The files and form collections are not mounted until the Save method is invoked, so it is incorrect to query these collections before calling Upload.Save.

Error!
Upload.Save (Upload.form ("Path"))
Limit file Size
Maybe you need to limit the size of the uploaded file to prevent server disk space from clogging up. All you have to do is call Setmaxsize in your upload object before calling Save:
Set Upload = Server.CreateObject ("Persits.upload.1")
Upload.setmaxsize 50000, False
Upload.Save "C:\Upload"

In this example, we limit the size of the uploaded file to 50000 bytes. The Second optional parameter specifies whether the part that exceeds the maximum range of the file should be deleted (if set to false or not) or rejected as an error exception (if set to true).



Enforce a unique file name
By default, AspUpload overwrites the files already in the upload path. If you don't want to, you can configure the component to generate a unique name for uploading files to prevent overwriting existing files. To set the Overwritefiles property of the upload manager before calling Save:

Upload.overwritefiles = False

The default value is true.

To prevent name collisions, AspUpload adds an integer enclosed in parentheses after the original file name. For example, if the file MyFile.txt already exists in the upload directory, and another file with the same name is being uploaded, AspUpload will save the new file as MyFile (1). txt. If we upload more MyFile.txt, they will be stored MyFile (2). txt, MyFile (3). txt, and so on.


Moving, copying, and deleting files
The file Upload object provides some means for you to move, copy, or delete uploaded files. These methods are
File. Move (NewName as String)
File. Copy (NewLocation as String, Optional Overwrite)
File. Delete

Depending on the newname parameter, the Move method moves the file to a different directory or renames him. Suppose the file Abc.txt uploaded to the directory
C:\Upload. Then call

File. Move "C:\WINNT\abc.txt" moves the file to C:\WINNT and calls the
File. Move "C:\Upload\xyz.txt" only changes the file name.

It is important to know that the move method has a side effect: When this method is successfully invoked, the Path property of the file object will point to the new directory/name.

The Copy property copies the file to the new directory/name. The new directory must be a fully legal path. If the overwrite parameter is set to TRUE or is not set, the Copy method is instructed to overwrite the existing file in the new directory. If set to False, the method fails when the file already exists in the new directory. Unlike the Move method, this method does not affect the Path property.

Sometimes you might choose to use the Delete method, for example, when you save a file as a blobs in a database and you no longer need it in your upload path. Saving the file to the database is our next topic to discuss.



Storing files as BLOBs in a database
Many database management systems like MS Access or SQL Server will allow you to save any file as "binary Large Objects" (BLOBs). An MS Access table can hold a binary file in an OLE Object-type data field. In SQL Server, the corresponding data type is image. The stored files can be retrieved for downloading later, or shown in ADO.
AspUpload allows you to upload files to the database using just one line of code! Let's take a look at the third set of sample files. The file test3.htm is almost the same as test1.htm, so we no longer show it here. File uploadscript4.asp is worth our attention:

<HTML>
<BODY>
<%
Set Upload = Server.CreateObject ("Persits.upload.1")
Upload.Save "C:\Upload"
On Error Resume Next
For each File in Upload.files

File.todatabase "Dsn=data; Uid=sa; Pwd=xxx "," INSERT into Blobs (ID, Path, Bigblob) VALUES (A, ' "& File.path &" ',?) "
If ERR <> 0 Then
Response.Write "Error Saving the file:" & Err.Description
Else
File.delete
Response.Write "Success!"
End If

Next
%>
</BODY>
</HTML>



This line

On Error Resume Next

Indicates that the ASP does not display an error message when it occurs outside, only stores the unexpected code and description in the built-in Err object, and continues the execution of the script.

Next line

File.todatabase "Dsn=data; Uid=sa; Pwd=xxx "," INSERT into Blobs (ID, Path, Bigblob) VALUES (A, ' "& File.path &" ',?) "

Is everything that is used to store files in a database. Let's examine the two parameters of this method:

The first parameter is an ODBC connection string in the following format:

"Dsn=datasource; Uid=userid; Pwd=password;<other Optional Parameters> "

The second parameter is an SQL INSERT or UPDATE statement with a question mark (?) and can only be brought one. Its role is to provide a space container for the files to be stored. In this example, our lower database table blobs contains three columns: An integer ID, a varchar Path, and an image bigblob. This SQL INSERT statement puts 12 in the ID bar, the file path is placed in the path bar, and the real file is placed in the Bigblob column.

The next line checks that the statement is correct before successful execution. If successful, the Err object takes a value of 0 and deletes the file
(File.delete line), because the file has been stored in the database, no longer need to be placed in the upload path. Otherwise, err contains a numeric error code, and Err.Description contains a description of the unexpected language.


Storing GIF and JPEG images in a database is common. You don't need to use any Third-party components to take the image out of the database and display it in an HTML page. ADO will be able to complete the task.

Put the generic tag in your HTML page and point the SRC attribute to an ASP script, such as



The getimage.asp script might look like this

<%
Set db = Server.CreateObject ("ADODB.") Connection ")
Db. Open "Data"
Set rs =db. Execute ("SELECT Bigblob from Blobs where id =" & Request ("id"))
Response.ContentType = "Image/jpeg" (or "image/gif")
Response.BinaryWrite rs ("Bigblob")
%>


--------------------------------------------------------------------------------
Where can I get more information about AspUpload
To get a complete aspupload document and download a free evaluation version, visit the persists software company's web site
Http://www.persits.com/aspupload.html. The registration fee for this component is $99.00 (Single CPU protocol).
Questions that are often asked
Q: Can aspupload work on all ASP versions?
A: No. Earlier versions of the ASP's request object did not provide BinaryRead or TotalBytes methods, and this component relied heavily on both methods. The best way to check if your ASP version is allowed to upload is to perform a simple script like <% n = request.totalbytes%> to see if your ASP module can recognize it.

Q: Where can I get the latest version of ASP?
A: It depends on the version of your Web server. If you use PWS or IIS3.0, you can go to
http://www.microsoft.com/office/intranet/modules/asp411s3.asp Download the latest version. If you use IIS4.0 you can download and install option Pack 4 from Http://www.microsoft.com/iis.

Q: Does Microsoft Internet Explorer 3.0 support file uploads?
A: By default, it is not supported. However, there is a IE3 attachment can be used, from this download http://www.microsoft.com/msdownload/iebuild/ie3add_win32/en/ie3add_win32.htm.


About the author
Peter Persits (peter@persits.com) is the founder and president of Persits Software, Inc., Popular ASP Components Aspntuser, Aspgrid, Aspaccesscontrol, AspUpload and AspEmail's author. Peter has been involved in software development for more than 10 years. He has a master's degree in computer Science from American University (Washington, DC) and is a Microsoft Certified Solution Developer. He now lives in Arlington, VA.


Related Article

Alibaba Cloud 10 Year Anniversary

With You, We are Shaping a Digital World, 2009-2019

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.