如何使用 ASP 時,將檔案上載到網頁伺服器

文章編號: 299692 - 檢視此文章適用的產品。
全部展開 | 全部摺疊

在此頁中

對於 Microsoft Visual Basic。NET 版本,這份文件的詳細資訊,請參閱 315832.

結論

本文將告訴您如何啟用您的 Web 伺服器接收來自 Microsoft 動態伺服器網頁 (asp) 的檔案傳輸,藉由使用伺服器端 Microsoft COM + 元件。

附註: Visual Basic 6 開發的 Microsoft 支援範圍已變更。如需詳細資訊,請參閱http://msdn.microsoft.com/en-us/vstudio/ms788708。

需求

  1. Microsoft Windows 2000 和 Microsoft 網際網路資訊伺服器 5.0 (IIS) 安裝和設定
  2. 開發軟體的電腦是否比另一台電腦伺服器上,您必須擁有有效的網路或網際網路連線到伺服器,主控 ASP 網頁。

Microsoft Visual Basic 6 專案安裝程式和程式碼

  1. 開始 Visual Basic,然後重新啟動新的 ActiveX DLL專案。
  2. 為專案的名稱ASPFileUpload.
  3. 變更名稱 類別 1 若要檔案.
  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. 將會收到的 Web 伺服器上建立資料夾例如,上載的檔案C:\TEMP\AspFileUpload.
  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 根資料夾重要事項。
  15. 編輯 Uploadfile.asp,以反映的目標資料夾您在步驟 1 中建立的資料夾。目標資料夾的工作分派位於下列程式碼行:
    fuFile.Target = "C:\TEMP\AspFileUpload\"
    					

上傳檔案

  1. 在 Web 瀏覽器中開啟 Postfile.asp 頁面上的下列 URL:
    http://YourWebServer/Postfile.asp
  2. 選取您要上載,然後按一下想要的檔案上載.
  3. 請檢查您的 [上載] 資料夾。您上載的檔案會出現在此資料夾中。

疑難排解

  • 如果未輸入檔案名稱,而且您嘗試送出[Postfile.asp] 頁面中,您會收到 「 一般 」、 「 伺服器端的錯誤訊息。您可能會想要修改程式碼,在其中一個提供更好記的錯誤訊息用戶端這邊,或在伺服器端。
  • 如果您需要大量上載容量,Microsoft建議您購買或建置可以編譯、 多執行緒元件更有效率地處理的負載比這個 Visual Basic 的元件。
  • 潛在的安全性風險存在,每當您允許使用者將檔案上載到您的 Web 伺服器。特別是如果您的伺服器在網際網路上,而且如果您允許匿名上載。您必須正確設定 Windows 權限及 IIS 使用者驗證,並確定您為使用者提供所需的存取權。這點很重要的以便您不這樣做讓使用者能夠透過略過的安全性控制存取程式系統。

屬性

文章編號: 299692 - 上次校閱: 2012年1月4日 - 版次: 0.1
這篇文章中的資訊適用於:
  • Microsoft Active Server Pages 4.0
  • Microsoft Internet Information Services 5.0
關鍵字:?
kbaspobj kbcodesnippet kbconfig kbdeployment kbfile kbfso kbguidelines kbhowto kbsample kbscript kbsecurity kbserver kbsetup kbwebserver kbmt KB299692 KbMtzh
機器翻譯
重要:本文是以 Microsoft 機器翻譯軟體翻譯而成,而非使用人工翻譯而成。Microsoft 同時提供使用者人工翻譯及機器翻譯兩個版本的文章,讓使用者可以依其使用語言使用知識庫中的所有文章。但是,機器翻譯的文章可能不盡完美。這些文章中也可能出現拼字、語意或文法上的錯誤,就像外國人在使用本國語言時可能發生的錯誤。Microsoft 不為內容的翻譯錯誤或客戶對該內容的使用所產生的任何錯誤或損害負責。Microsoft也同時將不斷地就機器翻譯軟體進行更新。
按一下這裡查看此文章的英文版本:299692
Microsoft及(或)其供應商不就任何在本伺服器上發表的文字資料及其相關圖表資訊的恰當性作任何承諾。所有文字資料及其相關圖表均以「現狀」供應,不負任何擔保責任。Microsoft及(或)其供應商謹此聲明,不負任何對與此資訊有關之擔保責任,包括關於適售性、適用於某一特定用途、權利或不侵權的明示或默示擔保責任。Microsoft及(或)其供應商無論如何不對因或與使用本伺服器上資訊或與資訊的實行有關而引起的契約、過失或其他侵權行為之訴訟中的特別的、間接的、衍生性的損害或任何因使用而喪失所導致的之損害、資料或利潤負任何責任。

提供意見