【发布时间】:2019-12-19 21:59:59
【问题描述】:
我正在尝试通过 Mac Excel VBA 通过 curl 发送图像文件。我从How do I issue an HTTP GET from Excel VBA for Mac 那里得到了很大的帮助,而且我的大部分工作都在工作。我可以通过邮件发送数据并获得服务器响应。
但是,当我尝试上传文件时代码失败。
这是从终端应用程序完美执行的 curl 字符串示例:
curl -H "apikey:helloworld" --form "file=@/Various/ImageTest/Puzzle2.smaller.jpg" https://api.ocr.space/Parse/Image
注意路径名必须以“@”开头,顶层是根目录。图像文件也是我 Mac 上的图像,但如果您尝试测试上述内容,只需指向您的任何图像文件。
服务器响应上述内容。
但是,当我采用相同的代码并将其放入 VBA 时,它会失败。除了加载文件之外,我在所有方面都取得了成功。但是当我尝试上传文件时,我得到一个代码 6656 返回,没有别的。我不相信 6656 来自服务器,我认为它来自我的 Mac。
这是一个例子
Sub RunTest2()
Dim result As String
Dim exitCode As Long
Dim Stringtest As String
Dim StringToSend As String
StringToSend = "curl -H 'apikey:helloworld' --form 'file=@/Various/ImageTest/Puzzle2.smaller.jpg' https://api.ocr.space/Parse/Image"
result = execShell(StringToSend, exitCode)
Debug.Print "Result: " & result
Debug.Print "Exit Code: " & Str(exitCode)
End Sub
上面的 execShell 例程与 How do I issue an HTTP GET from Excel VBA for Mac 中的例程相同。这是代码:
Option Explicit
' execShell() function courtesy of Robert Knight via StackOverflow
' http://stackoverflow.com/questions/6136798/vba-shell-function-in-office-2011-for-mac
Private Declare PtrSafe Function popen Lib "libc.dylib" (ByVal command As String, ByVal mode As String) As LongPtr
Private Declare PtrSafe Function pclose Lib "libc.dylib" (ByVal file As LongPtr) As Long
Private Declare PtrSafe Function fread Lib "libc.dylib" (ByVal outStr As String, ByVal size As LongPtr, ByVal items As LongPtr, ByVal stream As LongPtr) As Long
Private Declare PtrSafe Function feof Lib "libc.dylib" (ByVal file As LongPtr) As LongPtr
Function execShell(command As String, Optional ByRef exitCode As Long) As String
Dim file As LongPtr
file = popen(command, "r")
If file = 0 Then
Exit Function
End If
While feof(file) = 0
Dim chunk As String
Dim read As Long
chunk = Space(50)
read = fread(chunk, 1, Len(chunk) - 1, file)
If read > 0 Then
chunk = Left$(chunk, read)
execShell = execShell & chunk
End If
Wend
exitCode = pclose(file)
End Function
Function HTTPGet(sUrl As String, sQuery As String) As String
Dim sCmd As String
Dim sResult As String
Dim lExitCode As Long
sCmd = "curl --get -d """ & sQuery & """" & " " & sUrl
sResult = execShell(sCmd, lExitCode)
' ToDo check lExitCode
HTTPGet = sResult
End Function
认为问题可能出在字符串格式上,我尝试了双引号、单引号和 ascii chr(34),但没有任何改变。我还尝试了 @ 符号的 ascii。 如果我删除@,那么我确实会从服务器收到响应,但响应是“文件”参数错误。 不知何故,文件没有被正确加载,即使相同的代码在终端上工作。我认为这可能是权限问题。 任何帮助表示赞赏。
【问题讨论】: