Automatic file upload using IE+ADO without user interaction - VBSscript
ActiveX RegEdit.   ActiveX User account Manager   Pure-ASP Upload
Export MDB/DBF from ASP   Active LogFile   WebChecker   ActiveX/ASP Multi Dictionary object
 See 
 also 
 IISTracer, real-time IIS monitor and logging tool.
 Huge ASP file upload with progress bar. 



Do you like this article?
Please, rate it
and write review!
Rated:
by Aspin.com users
What do you think?
 Top messages
 4.5.2002 9:16:43 
 Send an email from ASP (WSH) using VBSscript, CDONTS and Outlook. (nbsp;ASP / ASP.NetWSHVBScriptEmail)
 22.3.2003 19:18:41 
 Read and write SQL image data, store binary file to sql table. (nbsp;WSHDatabaseConversionVBScript)
 3.1.2001 13:00:48 
 Base64 encode VBS function (vb encoder algorithm), source code (nbsp;ConversionVBScript)

 Automatic file upload using IE+ADO without user interaction - VBSscript 

 Areas>Languages>VBScript
 Areas>ASP / ASP.Net>File & data transfer
 Areas>WSH

      To upload specific file using VBS/ASP with client-side compression see Zlib class of ScriptUtilities library and its upload sample.

      The previous article was about uploading files using VBA and IE. But what to do if you have only VBS (in WSH, IE or ASP)? VBS does not have functions which can work with binary data so you cannot read contents of a file from disk.
      But you can use several objects which lets you work with binary data (one of them is also on this site, ScriptUtilities). ADODB, which is included in a free microsoft data access sofware (MDAC), enables the work with binary data also.
      You can use ScriptUtils.ASPForm to accept uploaded files in ASP. ScriptUtils.ASPForm contains hi-performance, low resources consumption algorithm which can accept up to 2GB of data.

      1. There are some steps to upload file using http and multipart/form-data document. First of all we have to read file from a disk. We can use Scripting.FileSystemObject to read text data, or ADODB.Stream to read any file. The GetFile function does the work using ADODB.Stream.
      2. The second task we need to complette is a build of multipart/form-data document. The document contains from several fields separated by boundary. Each of the fields has its own header, which contains information about field name, file name and content-type of the source file. ADO Recordset object has a great method AppendChunk, which lets you join parts of multipart/form-data document (open boundary + headers + file contents + close boundary). You can see the code in BuildFormData function.
      3. Last task is send the multipart/form-data document as a post request to server with multipart/form-data Content-Type header. We can use at least two object to send POST request - XMLHttp or InternetExplorer. This script uses Navigate method of InternetExplorer.Application object. You can see the code in IEPostBinaryRequest function
 
      You can accept the uploaded file using ASP and Pure ASP file upload with progress :
<%
'Create upload form
'Using Huge-ASP file upload
'Dim Form: Set Form = CreateObject("ScriptUtils.ASPForm")
'or Using Pure-ASP file upload
Dim Form: Set Form = New ASPForm %>
<!--#INCLUDE FILE="_upload.asp"--><% 

Const fsCompletted  = 0

If Form.State = fsCompletted Then 'Completted
  'Get a destination folder
  DestFolder = Server.MapPath(".")

  'Save source files on server-side
  Form.Files.Save DestFolder
End If
%>

      Next vbs code is complette vbs file which lets you upload any file from client computer to server using http protocol and multipart/form-data form (form with input type=file). You can copy the code to file named fupload.vbs. Then you can use:
use
[cscript|wscript] fupload.vbs file url [fieldname]
  file ... Local file to upload
  url ... URL which can accept uploaded data
  fieldname ... Name of the source form field.
      UploadFile function can be also used in any other vbs envinronment, for example in ASP application, WSH, or in HTA application.       I used Internet Explorer to send binary data (Function IEPostBinaryRequest), because Internet Explorer is installed on each computer with Windows. But remember, that using of the object is NOT ideal. See Post binary data to URL from WSH/ASP/VBA/VBS article. The article contains some better alternative objects, which lets you send binary data to remote script.
'Upload file using http protocol And multipart/form-data
'v1.01
'2001 Antonin Foller, PSTRUH Software
do_vbsUpload

Sub do_vbsUpload()
  'We need at least two arguments (File + URL)
  If WScript.Arguments.Count < 2 Then InfoEcho
  
  'Are some required objects missing?
  If InStr(CheckRequirements, "Error") > 0 Then InfoEcho
  
  Dim FileName, DestURL, FieldName
  FieldName = "FileField" 'Default field name
  
  Dim aCounter, Arg
  aCounter = 1 'Argument counter
  For Each Arg In WScript.Arguments
    Select Case aCounter
      Case 1: FileName = Arg
      Case 2: DestURL = Arg
      Case 3: FieldName = Arg
    End Select
    aCounter = aCounter + 1
  Next
  
  UploadFile DestURL, FileName, FieldName
End Sub



'******************* upload - begin
'Upload file using input type=file
Sub UploadFile(DestURL, FileName, FieldName)
  'Boundary of fields.
  'Be sure this string is Not In the source file
  Const Boundary = "---------------------------0123456789012"
  
  Dim FileContents, FormData
  'Get source file As a binary data.
  FileContents = GetFile(FileName)
  
  'Build multipart/form-data document
  FormData = BuildFormData(FileContents, Boundary, FileName, FieldName)
  
  'Post the data To the destination URL
  IEPostBinaryRequest DestURL, FormData, Boundary
End Sub

'Build multipart/form-data document with file contents And header info
Function BuildFormData(FileContents, Boundary, FileName, FieldName)
  Dim FormData, Pre, Po
  Const ContentType = "application/upload"
  
  'The two parts around file contents In the multipart-form data.
  Pre = "--" + Boundary + vbCrLf + mpFields(FieldName, FileName, ContentType)
  Po = vbCrLf + "--" + Boundary + "--" + vbCrLf
  
  'Build form data using recordset binary field
  Const adLongVarBinary = 205
  Dim RS: Set RS = CreateObject("ADODB.Recordset")
  RS.Fields.Append "b", adLongVarBinary, Len(Pre) + LenB(FileContents) + Len(Po)
  RS.Open
  RS.AddNew
    Dim LenData
    'Convert Pre string value To a binary data
    LenData = Len(Pre)
    RS("b").AppendChunk (StringToMB(Pre) & ChrB(0))
    Pre = RS("b").GetChunk(LenData)
    RS("b") = ""
    
    'Convert Po string value To a binary data
    LenData = Len(Po)
    RS("b").AppendChunk (StringToMB(Po) & ChrB(0))
    Po = RS("b").GetChunk(LenData)
    RS("b") = ""
    
    'Join Pre + FileContents + Po binary data
    RS("b").AppendChunk (Pre)
    RS("b").AppendChunk (FileContents)
    RS("b").AppendChunk (Po)
  RS.Update
  FormData = RS("b")
  RS.Close
  BuildFormData = FormData
End Function

'sends multipart/form-data To the URL using IE
Function IEPostBinaryRequest(URL, FormData, Boundary)
  'Create InternetExplorer
  Dim IE: Set IE = CreateObject("InternetExplorer.Application")
  
  'You can uncoment Next line To see form results
  'IE.Visible = True
   
  'Send the form data To URL As POST multipart/form-data request
  IE.Navigate URL, , , FormData, _
    "Content-Type: multipart/form-data; boundary=" + Boundary + vbCrLf

  Do While IE.Busy
    Wait 1, "Upload To " & URL
  Loop
  
  'Get a result of the script which has received upload
  On Error Resume Next
  IEPostBinaryRequest = IE.Document.body.innerHTML
  IE.Quit
End Function

'Infrormations In form field header.
Function mpFields(FieldName, FileName, ContentType)
  Dim MPTemplate 'template For multipart header
  MPTemplate = "Content-Disposition: form-data; name=""{field}"";" + _
   " filename=""{file}""" + vbCrLf + _
   "Content-Type: {ct}" + vbCrLf + vbCrLf
  Dim Out
  Out = Replace(MPTemplate, "{field}", FieldName)
  Out = Replace(Out, "{file}", FileName)
  mpFields = Replace(Out, "{ct}", ContentType)
End Function


Sub Wait(Seconds, Message)
  On Error Resume Next
  CreateObject("wscript.shell").Popup Message, Seconds, "", 64
End Sub


'Returns file contents As a binary data
Function GetFile(FileName)
  Dim Stream: Set Stream = CreateObject("ADODB.Stream")
  Stream.Type = 1 'Binary
  Stream.Open
  Stream.LoadFromFile FileName
  GetFile = Stream.Read
  Stream.Close
End Function

'Converts OLE string To multibyte string
Function StringToMB(S)
  Dim I, B
  For I = 1 To Len(S)
    B = B & ChrB(Asc(Mid(S, I, 1)))
  Next
  StringToMB = B
End Function
'******************* upload - end

'******************* Support
'Basic script info
Sub InfoEcho()
  Dim Msg
  Msg = Msg + "Upload file using http And multipart/form-data" & vbCrLf
  Msg = Msg + "Copyright (C) 2001 Antonin Foller, PSTRUH Software" & vbCrLf
  Msg = Msg + "use" & vbCrLf
  Msg = Msg + "[cscript|wscript] fupload.vbs file url [fieldname]" & vbCrLf
  Msg = Msg + "  file ... Local file To upload" & vbCrLf
  Msg = Msg + "  url ... URL which can accept uploaded data" & vbCrLf
  Msg = Msg + "  fieldname ... Name of the source form field." & vbCrLf
  Msg = Msg + vbCrLf + CheckRequirements
  WScript.Echo Msg
  WScript.Quit
End Sub

'Checks If all of required objects are installed
Function CheckRequirements()
  Dim Msg
  Msg = "This script requires some objects installed To run properly." & vbCrLf
  Msg = Msg & CheckOneObject("ADODB.Recordset")
  Msg = Msg & CheckOneObject("ADODB.Stream")
  Msg = Msg & CheckOneObject("InternetExplorer.Application")
  CheckRequirements = Msg
'  MsgBox Msg
End Function

'Checks If the one object is installed.
Function CheckOneObject(oClass)
  Dim Msg
  On Error Resume Next
  CreateObject oClass
  If Err = 0 Then Msg = "OK" Else Msg = "Error:" & Err.Description
  CheckOneObject = oClass & " - " & Msg & vbCrLf
End Function
'******************* Support - end
 
 

See also for 'Automatic file upload using IE+ADO without user interaction - VBSscript' article:

     Download multiple files in one http request This article shows a way to download multiple files in one http request. It let's you send an HTML page along with image preview, prepare more files for download and send the files as one data stream. One request, one authentication per multiple files.
     Post binary data to URL from WSH/ASP/VBA/VBScript. Two methods to POST binary or string data to external URL and read results sent from a script on the URL.
     Automated file upload using IE, without user interaction - VBA Lets you send file from a client to www server over http connection using IE. The file is sent as a result of type=file form field.

If you like this page, please include next link on your pages:
<A
 Href="http://www.motobit.com/tips/detpg_uploadvbsie/"
 Title="Lets you upload file from a
  client to www server over
  http connection using vbs, IE
  and ADODB. The file is
  sent as a result of
  type=file form field encoded multipart/form-data."
>Automatic file upload using IE+ADO without user interaction - VBSscript</A>

     IISTracer - IIS ISAPI real-time monitor IISTracer is a real-time monitoring tool for Microsoft IIS, which will show/log you what is happenning on IIS server right now. It let's you reveal problems with long-running scripts (.asp, .cgi, cfm...), hang-up states and low resource situations and lets you stop long-running requests (uploads/downloads).      ActiveX User account Manager - Set of simple objects for creating, deleting, and managing user accounts, groups, servers and domains in the Windows NT environment.
     Active log file - Hi-performance text file logging for ASP/VBS/VBA applications. Lets you create daily/weekly/monthly log files with variable number of logged values and extra timing and performance info.      ActiveX windows registry editor - Intuitive, easy to use COM interface to windows registry. Set of classes to read/enumerate/modify windows registry keys and values from ASP, VBS and T-SQL.
     ActiveX/ASP Multi Dictionary object - Free-threaded hi-speed dictionary algorithm with unique/nonunique keys (map/multimap). Connect to another dictionary object in the same process. Lock and Unlock methods to synchronize tasks (application scope). Share ASP Application/Session objects.      Export DBF/MDB from ASP - Conversion from recordset to MDB/DBF. Direct binary output of MDB or DBF files from ASP pages with one row of code.
     Pure-ASP upload - lets you upload files using Pure ASP VBS code (using multipart/form-data and input type=file).      ByteArray - Works with safearray binary data (VT_UI1 | VT_ARRAY) - save/restore binary data from disk, find, work with code pages, convert to string/hexstring(SQL).
     WebChecker - Checks http, https, ftp and gopher internet connections in regular intervals. Lets you monitor web site functionality (uptime). Enables restart or notification on problems.      HTTPLog ISAPI filter - Lets you log incomming/outgoing http header and document data to separate files. Monitor of IIS service input/output.

© 1996 – 2012 Antonin Foller, PSTRUH Software, e-mail help@pstruh.cz
Motobit.com