日期:2009-05-20  浏览次数:21055 次

在上次贴出的文章中我提到了几种上载组件的比较
现在我们自己动手,丰衣足食,来建立自己的上载组件
这个上载组件应该具备以下功能:
1。应该能够接受各种HTML的form元素中传过来的数值,而不
用知道是通过text或则select传过来的
2。应该能够给出一个上载路径
3。应该能够限制上载文件的大小
4。应该能够支持多个文件同时上载
5。应该能够处理异常错误
6。应该能够工作稳定
7。应该能够不厚此薄彼(即能够同时工作在IE和Netscape中)
8。能够把文件保存在数据库中
9。应该能够限制用户权限

代码和文件如下所示(老规矩,我就不作详细解释了)
1。Upload.htm

<HTML>
<HEAD><TITLE>Upload</TITLE></HEAD>
<BODY>
<FORM NAME="frmUpload" METHOD="Post" ENCTYPE="multipart/form-data" ACTION="Upload.asp"> <TABLE>
<TR><TD>作者</TD><TD><INPUT TYPE="text" NAME="txtAuthor"></TD></TR>
<TR><TD>文件</TD><TD><INPUT TYPE="file" NAME="txtFileName"></TD></TR>
<TR><TD COLSPAN="2" ALIGN="right"><INPUT TYPE="Submit" VALUE="Upload"></TD></TR>
</TABLE>
</FORM>
</BODY>
</HTML>


**注意:使用ENCTYPE="multipart/form-data"是为了能够让form提交一个文件

2。Upload.asp

<%@ Language=VBScript %>

<%
Option explicit
Response.Buffer = True
On Error Resume Next

If Request.ServerVariables("REQUEST_METHOD") = "POST" Then

    Dim objUpload
    Dim lngMaxFileBytes
    Dim strUploadPath
    Dim varResult

    lngMaxFileBytes = 10000
    strUploadPath = "c:\inetpub\wwwroot\upload\"
    Set objUpload = Server.CreateObject("pjUploadFile.clsUpload")
    If Err.Number <> 0 Then
        Response.Write "组件没有安装正确。"
    Else
        varResult = objUpload.DoUpload (lngMaxFileBytes, strUploadPath)
        Set objUpload = Nothing
        Dim i
        For i = 0 to UBound(varResult,1)
            Response.Write varResult(i,0) & " : " & varResult(i,1) & "<br>"
        Next

    End If
End If
%>


现在使用VB6开发这个ActiveX控件:(要注意的是,由于本人比较懒,中间有些代码可能不完整,
但重要的是要理解这个组件的编程思路)
1。引用Active Server Pages Object library.
2。代码如下:

Option Explicit

Private MyScriptingContext As ScriptingContext
Private MyRequest As Request
Private MyResponse As Request

Private Const ERR_NO_FILENAME As Long = vbObjectError + 100
Private Const ERR_NO_EXTENSION As Long = vbObjectError + 101
Private Const ERR_EMPTY_FILE As Long = vbObjectError + 102
Private Const ERR_FILESIZE_NOT_ALLOWED As Long = vbObjectError + 103
Private Const ERR_FOLDER_DOES_NOT_EXIST As Long = vbObjectError + 104
Private Const ERR_FILE_ALREADY_EXISTS As Long = vbObjectError + 105


Public Sub OnStartPage(PassedScriptingContext As ScriptingContext)
    Set MyScriptingContext = PassedScriptingContext
    Set MyRequest = MyScriptingContext.Request
    Set MyResponse = MySriptingContext.Response
End Sub

Private Function GetFileName(strFilePath) As String
    Dim intPos As Integer
    
    GetFileName = strFilePath
    For intPos = Len(strFilePath) To 1 Step -1
        If Mid(strFilePath, i