2

I would like to upload an Excel xlsm file to a php script from VBA. I found the following code:

Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")

Dim strURL As String
Dim StrFileName As String
Dim FormFields As String
Dim path As String
Dim name As String

   StrFileName = "c:\temp\ctc1output.xls"
   strURL = "http://www.tri-simulation.com/P3/"


   WinHttpReq.Open "POST", strURL, False


   ' Set the header
  WinHttpReq.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"


   FormFields = """fileulp=" & StrFileName & """"
   FormFields = FormFields + "&"
   FormFields = FormFields + """sfpath=P3"""

   WinHttpReq.Send FormFields


   ' Display the status code and response headers.
   MsgBox WinHttpReq.GetAllResponseHeaders
   MsgBox WinHttpReq.ResponseText
  1. Should I handle the file as a binary file or another type of file?
  2. Can I upload the file while it is still open (I want to upload the file from which the VBA is running from)?

I am not sure if I'm on the right track. I'm also not sure about what the headers and form fields should be.

Thx for any help.

Community
  • 1
  • 1
Albertus
  • 911
  • 2
  • 10
  • 19
  • 1
    HI, from your code, you are only sending the file name to server. You need to somehow convert the file into binaries and include them in your POST message. – Larry Mar 14 '13 at 09:33
  • Hi, I can see that the file has to be uploaded as a binary file. I'm using the code from [here](http://wqweto.wordpress.com/2011/07/12/vb6-using-wininet-to-post-binary-file/). It also seems i dont need to make a copy. My problem now is that I need send some text with the post. Will that be a seperate request or can I include it somehow with the first one? Sorry if I seem redundant, but this is my first time with this topic. – Albertus Mar 14 '13 at 10:53
  • 2
    you'll have to simulate a browser assembling a POST request and base64-encode your file, which can be done but is a bit tedious. another option would be to run [curl](http://curl.haxx.se/) which only needs the filename and the upload form parameters (the curl executable can be run from vba). – collapsar Mar 15 '13 at 19:37

1 Answers1

0

You won't need to base64 encode anything. Follow the sample code you have found but before preparing the file (before '---prepare body comment) just add your other texts (form entries) like this

sPostData = sPostData & "--" & STR_BOUNDARY & vbCrLf & _
     "Content-Disposition: form-data; name=""" & Name & """"
sPostData = sPostData & vbCrLf & vbCrLf & _
     pvToUtf8(Value) & vbCrLf

... where Name and Value are the designed name and the actual text that you want to include in service request. For the function pvToUtf8 implementation take a look at this Google Cloud Print service connector. The snippet above is taken from pvRestAddParam function of the same connector.

wqw
  • 11,771
  • 1
  • 33
  • 41