使用VBA以HTML格式通过<input \ input =“”/>上传文件

时间:2015-10-21 07:36:00

标签: html vba excel-vba upload image-uploading

我正在尝试将图片文件上传到OCR Site,但PDF文件无法上传到网站。

我使用以下代码来实现它,以下是HTML段:

Sub DownPDF()

    Dim FileName As String: FileName = "C:\Users\310217955\Documents\pdfdown\SGSSI001_HL1464_2011.pdf"
    Dim DestURL As String: DestURL = "https://www.newocr.com/"
    Dim FieldName As String: FieldName = "userfile"
    Call 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 Or IE.readyState <> 4
    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

这是HTML细分。

<input name="userfile" id="userfile" type="file">

2 个答案:

答案 0 :(得分:1)

您可以使用ScriptUtils.ASPForm接受ASP中的上传文件。 ScriptUtils.ASPForm包含高性能,低资源消耗算法,可以接受最多2GB的数据。

  1. 使用http和multipart / form-data文档上传文件有一些步骤。首先,我们必须从磁盘读取文件。我们可以使用Scripting.FileSystemObject来读取文本数据,或者使用ADODB.Stream来读取任何文件。 GetFile函数使用ADODB.Stream完成工作。

  2. 我们需要完成的第二项任务是构建multipart / form-data文档。该文档包含由边界分隔的多个字段。每个字段都有自己的标题,其中包含有关源文件的字段名称,文件名和内容类型的信息。 ADO Recordset对象有一个很好的方法AppendChunk,它允许你连接部分multipart / form-data文档(开放边界+标题+文件内容+关闭边界)。您可以在BuildFormData函数中看到代码。

  3. 上一个任务是将multipart / form-data文档作为post请求发送到具有multipart / form-data Content-Type标头的服务器。我们可以使用至少两个对象来发送POST请求 - XMLHttp或InternetExplorer。此脚本使用InternetExplorer.Application对象的Navigate方法。您可以在IEPostBinaryRequest函数中看到代码

  4. 请查看以下链接以获取更多信息。

    http://www.motobit.com/tips/detpg_uploadvbsie/

    GetFile方法将文件转换为UTF-8。 Pdf将超过128字节, 你需要将它转换为多字节字符串

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

    请参阅此页

    http://www.mrexcel.com/forum/excel-questions/861695-using-xmlhttp-upload-file-api.html#post4192153

答案 1 :(得分:0)

我花了几天时间尝试使用相同的技术 - 使用InternetExplorer.Application COM接口的Navigate方法上传文件。
Navigate的文档表明指定postdata参数将触发HTTP POST,但根据我的经验,Content-Type也是一个决定因素。使用Fiddler我发现当Content-Type = multipart / form-data时,它一直在发送GET HTTP方法而不是POST。

发送GET动词将告诉服务器忽略任何表单数据,并仅处理URI。

This page表示他在XMLHTTP对象上取得了一些成功,该对象允许更好地控制HTTP请求。这里有一些Powershell代码演示了这种技术:

$http = (New-Object -ComObject "MSXML2.XMLHTTP") 
$http.Open("POST",$DestURL,$false)
$http.SetRequestHeader("Content-Type", "multipart/form-data; boundary=" + $boundary)
$http.Send($PostData)