文章编号: 299692 - 最后修改: 2005年7月8日 - 修订: 5.5

濡備綍浣跨敤 ASP 文件上载到 Web 服务器

本页

展开全部 | 关闭全部
本文的是 Microsoft Visual Basic.net 版本的请参阅 315832? (http://support.microsoft.com/kb/315832/ )

概要

本文介绍如何启用 Web 服务器以接收来自 Microsoft 活动服务器页 (ASP) 页的文件传输,通过使用服务器端 Microsoft COM + 组件。

要求

  1. Microsoft Internet 信息与 Microsoft Windows 2000 Server 5.0 (IIS) 安装和配置
  2. 如果开发计算机是不同的计算机比服务器,您必须具有有效的网络或 Internet 连接到服务器承载 ASP 页。

Microsoft Visual Basic 6 项目设置和代码

  1. 启动 Visual Basic,然后开始一个新 ActiveX DLL 项目。
  2. 项目命名 ASPFileUpload
  3. 更改的 Class1 名称到 文件
  4. 项目 菜单上单击 引用
  5. 引用 对话框中单击以选择下列选项,然后单击 确定
    • 对于应用程序的 Visual Basic
    • Visual Basic 运行时对象和过程
    • Visual Basic 对象和过程
    • OLE 自动化
    • COM + 服务类型库
    • Microsoft 活动服务器页面对象库
    • Microsoft 脚本运行时
  6. 项目 菜单上单击 ASPFileUpload 属性
  7. 项目属性 对话框中单击以选择 无人参与执行内存中留存,然后单击 确定
  8. 将以下代码粘贴到 File.cls:
    Option Explicit
    
    Const ERR_INVALID_FILENAME = vbObjectError + 1000
    Const ERR_INVALID_TARGET = vbObjectError + 1001
    Const ERR_FILE_EXISTS = vbObjectError + 1002
    Const ERR_UPLOAD_CALLED = vbObjectError + 1003
    Const VB_ERR_PATH_NOT_FOUND = 76
    
    Private m_objContext As ObjectContext
    Private m_objRequest As ASPTypeLibrary.Request
    
    Private m_strTarget As String
    Private m_strFileName As String
    Private m_blnOverWrite As Boolean
    Private m_blnUploaded As Boolean
    Private m_lngTotalBytes As Long
    
    'All other form elements go here.
    Private m_formCol As Scripting.Dictionary
    
    Implements ObjectControl
    
    Private Function ObjectControl_CanBePooled() As Boolean
      ObjectControl_CanBePooled = False
    End Function
    
    Private Sub ObjectControl_Activate()
      Set m_objContext = GetObjectContext()
      Set m_objRequest = m_objContext("Request")
      Set m_formCol = New Scripting.Dictionary
    End Sub
    
    Private Sub ObjectControl_Deactivate()
      Set m_objContext = Nothing
      Set m_objRequest = Nothing
      Set m_formCol = Nothing
    End Sub
    
    Public Sub Upload()
      
      Const DEFAULT_CHUNK_SIZE = 262144 '256kb
      
      Dim bytBeginOfChunk() As Byte
      Dim bytEndOfChunk() As Byte
      Dim bytBeginOfName() As Byte
      Dim bytEndOfName() As Byte
      Dim bytBeginOfFile() As Byte
      Dim bytEndOfFile() As Byte
      Dim bytBeginOfValue() As Byte
      Dim bytEndOfValue() As Byte
      Dim bytName() As Byte
      Dim bytValue() As Byte
      Dim bytThisChunk() As Byte
      Dim bytFileName() As Byte
      Dim lngBeginOfChunk As Long
      Dim lngEndOfChunk As Long
      
      Dim lngBeginOfAttribute As Long
      Dim lngEndOfAttribute As Long
      Dim lngBeginOfValue As Long
      Dim lngEndOfValue As Long
      Dim blnEndOfData As Boolean
      Dim lngChunkSize As Long
      Dim lngBytesLeft As Long
      Dim lngFileNum As Long
      Dim strFileName As String
      
      On Error GoTo UploadErr
      
      If Uploaded Then
        Err.Raise ERR_UPLOAD_CALLED, App.Title, "The Upload method has already been called."
      End If
         
      bytBeginOfChunk = StrConv("-----------------------------", vbFromUnicode)
      bytEndOfChunk = StrConv("-----------------------------", vbFromUnicode)
      
      bytBeginOfName = StrConv("name=", vbFromUnicode) & ChrB(34)
      bytEndOfName = ChrB(34)
      
      bytBeginOfFile = StrConv("filename=", vbFromUnicode) & ChrB(34)
      bytEndOfFile = ChrB(34)
      
      bytBeginOfValue = ChrB(13) & ChrB(10) & ChrB(13) & ChrB(10)
      bytEndOfValue = ChrB(13) & ChrB(10) & StrConv("-----------------------------", vbFromUnicode)
         
      'Initialize the chunk size.
      If m_objRequest.TotalBytes <= DEFAULT_CHUNK_SIZE Then
        lngChunkSize = m_objRequest.TotalBytes
      Else
        lngChunkSize = DEFAULT_CHUNK_SIZE
      End If
        
      'Get the chunk from the request object.
      bytThisChunk = m_objRequest.BinaryRead(CVar(lngChunkSize))
    
      'Initialize the value.
      lngBeginOfChunk = 1
      
      'Repeat until the end of the data.
      Do While Not blnEndOfData
        'Begin the chunk.
        lngBeginOfChunk = InStrB(lngBeginOfChunk, bytThisChunk, bytBeginOfChunk) + UBound(bytBeginOfChunk)
        
        'Get name of the item.
        lngBeginOfAttribute = InStrB(lngBeginOfChunk, bytThisChunk, bytBeginOfName) + UBound(bytBeginOfName) + 1
        lngEndOfAttribute = InStrB(lngBeginOfAttribute, bytThisChunk, bytEndOfName)
        bytName = MidB(bytThisChunk, lngBeginOfAttribute, lngEndOfAttribute - lngBeginOfAttribute)
        
        'Get the value of the item.
        lngBeginOfValue = InStrB(lngEndOfAttribute, bytThisChunk, bytBeginOfValue, vbBinaryCompare) + UBound(bytBeginOfValue) + 1
        lngEndOfValue = InStrB(lngBeginOfValue, bytThisChunk, bytEndOfValue, vbBinaryCompare)
        
        If lngEndOfValue = 0 Then
          'The item extends the past current chunk.
          bytValue = MidB(bytThisChunk, lngBeginOfValue, lngChunkSize)
        Else
          'The item value exists in the current chunk.
          bytValue = MidB(bytThisChunk, lngBeginOfValue, lngEndOfValue - lngBeginOfValue)
        End If
        
        If UCase(StrConv(bytName, vbUnicode)) = "FILE" Then
          lngBeginOfAttribute = InStrB(lngBeginOfChunk, bytThisChunk, bytBeginOfFile, vbBinaryCompare) + UBound(bytBeginOfFile) + 1
          lngEndOfAttribute = InStrB(lngBeginOfAttribute, bytThisChunk, bytEndOfFile, vbBinaryCompare)
          
          bytFileName = MidB(bytThisChunk, lngBeginOfAttribute, lngEndOfAttribute - lngBeginOfAttribute)
          
          If UBound(bytFileName) < 0 Or UBound(bytValue) < 0 Then
            Err.Raise ERR_INVALID_FILENAME, App.Title, "Invalid File Name."
          End If
          
          If Me.Target = "" Then
            Err.Raise ERR_INVALID_TARGET, App.Title, "Invalid Target."
          End If
          
          'Use the original file name.
          If Me.FileName = "" Then
          
            'Trim the path from the file name.
            While InStrB(1, bytFileName, StrConv("\", vbFromUnicode), vbBinaryCompare) > 0
              bytFileName = MidB(bytFileName, InStrB(1, bytFileName, StrConv("\", vbFromUnicode)) + 1)
            Wend
            
            'Set the property.
            Me.FileName = StrConv(bytFileName, vbUnicode)
            
            'Convert the byte to Unicode.
            strFileName = Me.Target & Me.FileName
           
          Else
            strFileName = Me.Target & Me.FileName
          End If
          
          'Check for overwrite.
          If Me.OverWrite Then
            'This is the hack check. Make sure that wildcard characters cannot be used.
            If Not InStr(1, strFileName, "*") Then
              If FileExists(strFileName) Then
                Kill strFileName
              End If
            Else
              Err.Raise ERR_INVALID_FILENAME, App.Title, "The specified file name appears to be invalid."
            End If
          Else
            If FileExists(strFileName) Then
              Err.Raise ERR_FILE_EXISTS, App.Title, "The file already exists."
            End If
          End If
          
          lngFileNum = FreeFile
          
          Open strFileName For Binary Access Write As #lngFileNum
          
          'Write the file to the destination directory.
          Put #lngFileNum, , bytValue
    
          'This chunk is empty. Therefore, get a new chunk.
          lngBytesLeft = m_objRequest.TotalBytes - lngChunkSize
            
          'Start the chunking machine.
          Do While lngBytesLeft > 0
          
            'Get a new chunk.
            bytThisChunk = m_objRequest.BinaryRead(CVar(lngChunkSize))
                      
              lngEndOfValue = InStrB(1, bytThisChunk, bytEndOfValue, vbBinaryCompare)
              
              If lngEndOfValue > 0 Then
                'The item value exists in the current chunk.
                bytThisChunk = MidB(bytThisChunk, 1, lngEndOfValue - 1)
              End If
              
              'Append the chunk to the file.
              Put #lngFileNum, , bytThisChunk
              
              lngBytesLeft = lngBytesLeft - lngChunkSize
              
              If lngBytesLeft < lngChunkSize Then
                lngChunkSize = lngBytesLeft
              End If
            Loop
            
            Close #lngFileNum
            
            TotalBytes = FileLen(strFileName)
            
         ' Exit Do
         Else
          If UCase(StrConv(bytName, vbUnicode)) = "SAVEAS" Then
           Me.FileName = StrConv(bytValue, vbUnicode)
          Else 
           'form field other than file, such as textboxes 
           If UBound(bytValue) > 0 And UBound(bytName) > 0 Then 
            m_formCol.Add StrConv(bytName, vbUnicode), StrConv(bytValue, vbUnicode)
           Else
            m_formCol.Add StrConv(bytName, vbUnicode), ""
           End If
          End If
         End If
        
        'Get the next chunk.
        lngBeginOfChunk = lngEndOfValue
        
        If InStrB(lngBeginOfChunk, bytThisChunk, bytBeginOfName, vbBinaryCompare) = 0 Then
          blnEndOfData = True
        End If
      Loop
    
      Uploaded = True
      
      Exit Sub
      
    UploadErr:
      
      If Err.Number = VB_ERR_PATH_NOT_FOUND Then
        Err.Raise ERR_INVALID_TARGET, App.Title, "The Target specified does not exist."
      Else
        Err.Raise Err.Number, Err.Source, Err.Description
      End If
    End Sub
    
    Public Property Get Form() As Collection
        Set Form = m_formCol
    End Property
    Public Property Get FileName() As String
      FileName = m_strFileName
    End Property
    
    Public Property Let FileName(ByVal strNewValue As String)
      If Uploaded Then
        Err.Raise ERR_UPLOAD_CALLED, App.Title, "The Upload method has already been called."
      Else
        m_strFileName = strNewValue
      End If
    End Property
    
    Public Property Get OverWrite() As Boolean
      OverWrite = m_blnOverWrite
    End Property
    
    Public Property Let OverWrite(ByVal blnNewValue As Boolean)
      If Uploaded Then
        Err.Raise ERR_UPLOAD_CALLED, App.Title, "The Upload method has already been called."
      Else
        m_blnOverWrite = blnNewValue
      End If
    End Property
    
    Private Property Get Uploaded() As Boolean
      Uploaded = m_blnUploaded
    End Property
    
    Private Property Let Uploaded(ByVal blnNewValue As Boolean)
      m_blnUploaded = blnNewValue
    End Property
    
    Public Property Get Target() As String
      Target = m_strTarget
    End Property
    
    Public Property Let Target(ByVal NewValue As String)
      If Uploaded Then
        Err.Raise ERR_UPLOAD_CALLED, App.Title, "The Upload method has already been called."
      Else
        m_strTarget = NewValue
      End If
    End Property
    
    Private Function FileExists(ByVal FileName As String) As Boolean
      On Error GoTo FileExistsErr
      
      FileLen FileName
      FileExists = True
      Exit Function
      
    FileExistsErr:
      If Err.Number = VB_ERR_PATH_NOT_FOUND Then
        FileExists = False
      End If
    End Function
    
    Public Property Get TotalBytes() As Long
      TotalBytes = m_lngTotalBytes
    End Property
    
    Private Property Let TotalBytes(ByVal NewValue As Long)
      m_lngTotalBytes = NewValue
    End Property
    
  9. 编译该项目

ASP 代码

  1. 将以下代码粘贴到编辑器 (如记事本或 Microsoft Visual Interdev,然后将其另存为 PostFile.asp
    <%@ Language=VBScript %>
    <html>
    <head>
    </head>
    <body>
    <form enctype="multipart/form-data" action="uploadfile.asp" method="post" name="main1">
    <input name="file" type="file" size="50">
    <INPUT type="text" id=text1 name=text1><INPUT type="text" id=text2 name=text2>
    <input name="submit" type="submit" value="Upload">
    </form>
    </body>
    </html>
    
  2. 将下面的代码复制到编辑器 (如记事本或可视化 Interdev,然后将它保存为 UploadFile.asp
    <%@ Language=VBScript %>
    <%
      '//////////////////////////////////////////////////////////////////////////////////
      '//  ASPFileUpload.File API
      '//  
      '//  Properties
      '//     FileName
      '//       - Read/Write 
      '//       - The file will be saved with this file name. 
      '//       - This property can only be set before calling Upload.
      '//       - If no value is specified, the original file name
      '//       - in the HTTP post will be used.
      '//     
      '//     OverWrite
      '//       - Read/Write
      '//       - This property can only be set before calling Upload.
      '//       - If set to false and if the destination file exists, an error
      '//       - is raised. The default value is False.
      '//     
      '//     Target 
      '//       - Read/Write
      '//       - The file will be written to this folder.
      '//       - This property can only be set before calling Upload.
      '//       - There is no default value for this property and it is required.
      '//       
      '//      Form
      '//        - ReadOnly
      '//        - Scripting.Dictionary object
      '//        - Can access a specific item by using aspfileupload.Form("item").
      '//        - Acts like the asp form collection.
      '//        - Can enumerate all values in a collection with for each.
      '//        - Only filled after the Upload method is called.
      '//         
      '//  Methods
      '//     Upload
      '//       - This method parses the HTTP Post and writes the file.
      '//  
      '//  Other
      '//    - ASPFileUpload requires COM+
      '//    - Any call to the Request.Form() collection will cause the Upload
      '//      method to fail as the method references the Binary contents of the
      '//      Request object through the Request.BinaryRead method. 
      '//    - Also, if you access a variable in the Request collection without 
      '//      specifying the subcollection that it belongs to, the Request.Form collection 
      '//      may be searched. This causes an error in the Upload method.
      '//      
      '//////////////////////////////////////////////////////////////////////////////////
      
      Dim strMsg 'As String
      
     ' On Error Resume Next
      dim fuFile
      set fuFile = server.CreateObject("aspFileupload.file")  
      'Set the destination folder.
      fuFile.Target = "C:\TEMP\AspFileUpload\"
      fuFile.Upload
      
      If Err.number = 0 Then
        strMsg = fuFile.FileName  & " was uploaded successfully."
      Else
        strMsg = "An error occurred when uploading your file: " & Err.Description 
      End If
      for each o in fuFile.Form
    	Response.Write o  & "<BR>"
    	
    	next
    	
    	Response.Write fuFile.Form.item("text1") & "  :  " & fuFile.Form.item("text2")
    '  Response.Write Request.Form("test")
     set fufile = nothing
    %>
    <html>
    <head></head>
    <body>
    <%=strMsg%>
    </body>
    </html>

璁剧疆鏈嶅姟鍣

  1. 将接收上载的文件 C:\TEMP\AspFileUpload 如在 Web 服务器上创建一个文件夹。
  2. ASPFileUpload.dll 文件复制到 Web 服务器,然后将它注册通过在命令提示符处使用以下命令:
    regsvr32 PathToDLL \ASPFileUpload.dll
  3. 文件权限 (写访问权限) 适用于您希望能够上载文件的用户。
  4. 单击 开始,指向 设置,然后单击 控制面板
  5. 在控件面板中单击 管理工具,然后单击 组件服务 以打开组件服务 Microsoft 管理控制台 (MMC) 中。
  6. 展开 组件服务 节点、 计算机 节点、 我的电脑 节点和 COM + 应用程序 节点。
  7. 右击节点,指向 新建,然后单击 应用程序
  8. 安装或新建应用程序 对话框中单击 创建空应用程序、 命名应用程序,请确保单击以选择 服务器应用程序,然后单击 下一步
  9. 设置应用程序标识 对话框中单击 此用户,然后键入相应的用户帐户的凭据。 用户帐户必须将接收上载的文件的文件夹具有写访问权限。
  10. 单击 完成
  11. 展开您刚创建为此应用程序节点。
  12. 用鼠标右键单击该 nod、 指向 新建,然后单击 组件
  13. 单击 安装新组件,并找到该文件夹已保存并注册.dll 文件、 单击文件、 单击 下一步,和然后单击 完成
  14. Postfile.asp 的文件和 Uploadfile.asp 文件复制到您的 Web 根文件夹。 榛樿鎯呭喌涓嬶,Web 根文件夹是 C:\Inetpub\Wwwroot。
  15. 编辑 Uploadfile.asp 以反映您在步骤 1 中创建该文件夹的目标文件夹。 目标文件夹分配位于下面的代码行:
    fuFile.Target = "C:\TEMP\AspFileUpload\"
    					

上载文件

  1. 在 Web 浏览器中打开 Postfile.asp 页,在以下 URL:
    http:// YourWebServer /Postfile.asp
  2. 选择您要上载,一个文件,然后单击 上载
  3. 请检查您的上载文件夹。 您上载的文件将出现在此文件夹中。

鐤戦毦瑙 g 瓟

  • 如果不键入一个文件名,并尝试提交 Postfile.asp 页收到泛型、 服务器端的错误消息。 您可能需要修改代码以提供更友好的错误消息,在客户端或服务器端。
  • 如果需要高卷上载容量,Microsoft 建议您购买或生成比此 Visual Basic 组件可以更有效地处理负载的已编译的、 多线程组件。
  • 每当您允许用户将文件上载到您的 Web 服务器时,存在潜在的安全风险。 如果您的服务器是在 Internet 上,如果您允许匿名上载时尤其如此。 必须正确配置 Windows 权限和 IIS 用户身份验证,以确保您会向用户提供仅访问他们需要的。 这一点很重要,以便您不允许用户通过绕过安全控制您的系统的访问方式。

这篇文章中的信息适用于:
  • Microsoft Active Server Pages 4.0
  • Microsoft Internet Information Server 4.0
  • Microsoft Internet Information Services 5.0
关键字:?
kbmt kbaspobj kbcodesnippet kbconfig kbdeployment kbfile kbfso kbguidelines kbhowto kbsample kbscript kbsecurity kbserver kbsetup kbwebserver KB299692 KbMtzh
机器翻译机器翻译
注意:这篇文章是由无人工介入的微软自动的机器翻译软件翻译完成。微软很高兴能同时提供给您由人工翻译的和由机器翻译的文章, 以使您能使用您的语言访问所有的知识库文章。然而由机器翻译的文章并不总是完美的。它可能存在词汇,语法或文法的问题,就像是一个外国人在说中文时总是可能犯这样的错误。虽然我们经常升级机器翻译软件以提高翻译质量,但是我们不保证机器翻译的正确度,也不对由于内容的误译或者客户对它的错误使用所引起的任何直接的, 或间接的可能的问题负责。
点击这里察看该文章的英文版: 299692? (http://support.microsoft.com/kb/299692/en-us/ )
Microsoft和/或其各供应商对于为任何目的而在本服务器上发布的文件及有关图形所含信息的适用性,不作任何声明。 所有该等文件及有关图形均"依样"提供,而不带任何性质的保证。Microsoft和/或其各供应商特此声明,对所有与该等信息有关的保证和条件不负任何责任,该等保证和条件包括关于适销性、符合特定用途、所有权和非侵权的所有默示保证和条件。在任何情况下,在由于使用或运行本服务器上的信息所引起的或与该等使用或运行有关的诉讼中,Microsoft和/或其各供应商就因丧失使用、数据或利润所导致的任何特别的、间接的、衍生性的损害或任何因使用而丧失所导致的之损害、数据或利润不负任何责任。
 

文章翻译

 

Related Support Centers