如何使用VBA通过HTTP_POST发送Excel文件?

10
这里提出的问题:如何使用VBA从Excel向服务器发送HTTP POST请求?几乎正是我要找的内容,除了我正在尝试向服务器发送多个文件。我进一步搜索并找到如何使用VBA通过HTTP post上传zip文件?这也不错, 但相当令人沮丧 - 看起来需要大量工作(不只是在这里创建HTML表单...)。
这里的选项2:http://www.motobit.com/tips/detpg_post-binary-data-url/(如上面SO问题所述)似乎很好用,但由于我使用JS和CSS,我不知道如何在示例中创建FormData(要发送到服务器的二进制文件)。
请问有谁能帮助我吗?实质上,我想通过VBA从Excel内部通过HTTP_POST将3-6个文件发送到预期接收表单数据的Web服务器上的PHP脚本,例如。处理此事的HTML表单如下:
<form action="upload_file.php" method="post" enctype="multipart/form-data">
  <input name="userfile[]" type="file" /><br />
  <input name="userfile[]" type="file" /><br />
  <input name="userfile[]" type="file" /><br />
  <input type="submit" />
</form>

预先感谢大家。

编辑 - 2012年8月2日

我仍在努力解决这个问题。我不懂VBA/6,只会一点基本的JS,所以有点迷茫。到目前为止,我已经做了以下工作:

Sub HTTPInternetPutFile()

    ' create new object with WinHttpRequest for this operation
    Dim WinHttpReq As Object
    Set WinHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
    Dim FormFields As String

    ' initialize variables that we will set and pass as parameters
    Dim sfpath
    Dim strURL As String
    Dim StrFileName As String


       StrFileName = "CLIPrDL.csv"
       sfpath = "C:\CLIPr\"
       strURL = "http://s0106001c10187ab1.gv.shawcable.net/uploadtest/upload_file.php"


       WinHttpReq.Open "POST", strURL, False


       ' Set headers
       WinHttpReq.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
       WinHttpReq.setRequestHeader "Accept-Charset", "ISO-8859-1,utf-8"
       WinHttpReq.setRequestHeader "Content-Type", "multipart/form-data"
       ' WinHttpReq.setRequestHeader "Content-Type", "text/html;charset=UTF8"
       WinHttpReq.setRequestHeader "Content-Disposition", "form-data; name=""userfile[]"""

       ' I dont understand this... why use fileup??
       FormFields = """filename=" & StrFileName & """"
       FormFields = FormFields & "&"
       FormFields = FormFields & sfpath

       ' so comment it out for now
       ' WinHttpReq.Send FormFields
       WinHttpReq.Send sfpath & StrFileName

       ' output this var to a message box becuase I dont know what it does really
       MsgBox FormFields
       ' Display the status code and response headers.
       MsgBox WinHttpReq.GetAllResponseHeaders
       MsgBox WinHttpReq.ResponseText


End Sub

脚本底部的消息框会输出服务器的头部和回应(空白HTML页面)。我感觉有些地方没有在头部中进行正确的设置,以便让服务器满意(注意:尝试注释掉Content-Type)。

如果有任何人在使用VBA / 6中的WinHttpRequest对象通过HTTP POST二进制文件方面有经验,请帮忙!:)


文件的类型是什么:文本还是二进制? - Tim Williams
你能够逐个发送文件吗?或者这不是一个选项? - ikh
@TimWilliams 二进制,Excel 文件。 - jonathanbell
1
这是VB6的代码,但也适用于VBA/Excel:http://wqweto.wordpress.com/2011/07/12/vb6-using-wininet-to-post-binary-file/ - Tim Williams
@TimWilliams 我星期一会试试!谢谢! - jonathanbell
显示剩余2条评论
2个回答

16

如果您正在使用64位版本的Excel,则需要在声明函数中添加PtrSafe。例如:Private Declare PtrSafe Function InternetAutodial - Colin Stadig
我无法让这段代码运行... 我需要引用哪些库? - Colin Stadig

3

1
但是没有解释如何部署?一个例子会让这个更有用。 - QHarr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接