php 如何在Access中使用VBA将JPG上传到自己的Web服务器?

b1uwtaje  于 2023-02-11  发布在  PHP
关注(0)|答案(1)|浏览(158)

我有一些代码,但我不明白为什么它不工作...

Sub UploadJPGWithCURL()
    Dim winHttpReq As Object
    Dim fileData As String
    Dim boundary As String

    Dim fileName As String
    Dim filePath As String
    
    filePath = "Z:\Desktop\testimage.jpg"
    fileName = "testimage.jpg"

    boundary = "----------------------------" & Format(Now, "ddmmyyyyhhmmss")
    
    fileData = "--" & boundary & vbCrLf
    fileData = fileData & "Content-Disposition: form-data; name=""fileToUpload""; filename=""" & fileName & """" & vbCrLf
    fileData = fileData & "Content-Type: image/jpeg" & vbCrLf & vbCrLf
    'fileData = fileData & filePath & vbCrLf
    fileData = fileData & getBinaryFile(filePath) & vbCrLf
    fileData = fileData & "--" & boundary & "--" & vbCrLf
    
    Debug.Print fileData
    
    Set winHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
    
    winHttpReq.Open "POST", "[THE URL TO MY WEBSERVER PHP PAGE THAT IS GOING TO PROCESS THE UPLOAD]", False
    winHttpReq.setRequestHeader "Content-Type", "multipart/form-data; boundary=" & boundary
    winHttpReq.send (fileData)
    
    If winHttpReq.Status = 200 Then
      Debug.Print winHttpReq.ResponseText
    Else
      Debug.Print "Request failed with status code: " & winHttpReq.Status
    End If
End Sub

Function getBinaryFile(filePath)
  Dim binaryStream
  Set binaryStream = CreateObject("ADODB.Stream")
  binaryStream.Type = 1
  binaryStream.Open
  binaryStream.LoadFromFile filePath
  getBinaryFile = binaryStream.Read
  binaryStream.Close
End Function

在服务器PHP上,$_FILES数组给出了这个文件的错误代码3,看起来是部分上传......(如果在php代码的顶部打印$_FILES数组,我会得到这个错误代码......

Array
(
    [fileToUpload] => Array
        (
            [name] => testimage.jpg
            [full_path] => testimage.jpg
            [type] => 
            [tmp_name] => 
            [error] => 3
            [size] => 0
        )

)

任何帮助或指导将不胜感激!
谢谢
克里斯

nmpmafwu

nmpmafwu1#

您必须转换文件的二进制内容和发送的数据,如下所示:

Function getBinaryFile(filePath) As Variant
  Dim binaryStream As Variant
  Set binaryStream = CreateObject("ADODB.Stream")
  binaryStream.Type = 1
  binaryStream.Open
  binaryStream.LoadFromFile filePath
  getBinaryFile = StrConv(binaryStream.Read, vbUnicode) ' Convert to Unicode
  binaryStream.Close
End Function

发送数据时:
创建此函数:

Function ToByteArray(str As String) As Byte()
    ToByteArray = StrConv(str, vbFromUnicode)
End Function

并像这样使用它:

winHttpReq.send ToByteArray(fileData) ' Convert from Unicode

测试成功:

Array
(
    [fileToUpload] => Array
        (
            [name] => sample.jpg
            [type] => image/jpeg
            [tmp_name] => J:\tmp\php827.tmp
            [error] => 0
            [size] => 3287
        )
)

相关问题