我正在尝试将当前工作的Excel工作表发送到接受Content-type:“ multipart-form”的api。我需要帮助才能在vba中形成请求。以下是我的方法:
Sub sendInternalDataToAPI(myCSVFileName As String)
Dim data As Worksheet
Dim boundary As String
Dim filename As String
boundary = "--------------------------784780577729000449617522"
filename = "data"
Set data = ActiveWorkbook.Sheets("DATA")
'Set payload = preparePayload(data)
Url = "http://localhost:8080/load"
Set objHTTP = CreateObject("Microsoft.XMLHTTP")
With objHTTP
.Open "POST", Url, False
.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
.setRequestHeader "Content-type", "multipart/form-data;boundary=" & boundary
.send (preparePayload(data, boundary, myCSVFileName))
strResponseStatus = .StatusText
strResponse = .ResponseText
allResponseHeader = .GetAllResponseHeaders
End With
Debug.Print strResponseStatus
Debug.Print allResponseHeader
Debug.Print strResponse
End Sub
Function preparePayload(data As Worksheet, boundary As String, filename As String) As String
Debug.Print boundary & vbCrLf & _
"Content-Disposition: form-data; name=""data""; filename=""" & filename & """" & vbCrLf & _
"Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" & vbCrLf & _
data & vbCrLf & _
boundary & "--"
preparePayload = boundary & vbCrLf & _
"Content-Disposition: form-data; name=""data""; filename=""" & filename & """" & vbCrLf & _
"Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" & vbCrLf & _
data & vbCrLf & _
boundary & "--"
End Function
执行时出现以下错误:
VBA错误:438:对象不支持此属性或方法
表单主体中的变量“数据”导致错误。我不确定我想念的是什么!而且,我从邮递员那里获得了Content-type在request-body中,执行得很好!我是vba的新手,对您的帮助深表感谢。
谢谢!
UPDATE:来自邮递员控制台的邮递员请求是:
Request ---
POST <url>/load HTTP/1.1
User-Agent: PostmanRuntime/7.22.0
Accept: */*
Cache-Control: no-cache
Postman-Token: d3a4355f-548a-4b10-b8b7-53c62772cc4a
Host: localhost:8080
Content-Type: multipart/form-data; boundary=--------------------------360126624207643168890089
Accept-Encoding: gzip, deflate, br
Content-Length: 352982
Connection: keep-alive
----------------------------360126624207643168890089
Content-Disposition: form-data; name="data"; filename="test-excel.xlsx"
<test-excel.xlsx>
----------------------------360126624207643168890089--
Response---
HTTP/1.1 200 OK
Date: Tue, 03 Mar 2020 13:41:17 GMT
Content-Type: application/json
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Transfer-Encoding: chunked
response Body fromt the server--
{"data":true}
这如何只处理请求正文中的文件名而不处理内容?
我相信问题是您试图将Worksheet变量“ data”转换为preparePayload函数中的String。
我不确定您需要为使用的API“做准备”,如果它是工作表本身的名称,则可以使用.Name方法获取它,如果还有其他事情,则需要确保正确地将其转换为字符串,或确保可以将其隐式转换。
最后,完成!
正如@TimWilliams在评论中提到的,基本上我必须:1.首先从excel保存文件2.以String形式读回excel3.转换为字节,然后通过http
发送此帖子也提供了极大帮助:google.com/search?q=vba+post+excel+file+site:stackoverflow.com
此外,如果有一种方法可以将ActiveWorkbook.sheet(“ MY_SHEET”)直接发送到api,那真是太好了。将继续探索!
感谢@TimWilliams!