Send pdf/jpg file in http post request - server error - vb6

I want to send Image or pdf document in post request, the URL is working fine, but in visual basic I used the below code to send the document using url but It gives me failure response server error .
I have checked URL, it has no issue, but when I tried to implement in vb, in response I get the 500 server error
Dim strFile As String
Dim uploadDocUrl As String
Dim baBuffer() As Byte
Dim sPostData As String
Dim strFile As String
Dim strFileName As String
strFile = "C://Users/Avinashi/Desktop/1.pdf"
uploadDocUrl = "http://api.tally.messaging.bizbrain.in/api/v1/uploadFile"
strFileName = "1.pdf"
nFile = FreeFile
Open strFile For Binary Access Read As nFile
If LOF(nFile) > 0 Then
ReDim baBuffer(0 To LOF(nFile) - 1) As Byte
Get nFile, , baBuffer
sPostData = StrConv(baBuffer, vbUnicode)
End If
Close nFile
sPostData = "--" & STR_BOUNDARY & vbCrLf & _
"Content-Disposition: form-data;name=""1.pdf""; filename=""" & Mid$(strFile, InStrRev(strFile, "\") + 1) & """" & vbCrLf & _
"Content-Type:multipart/form-data" & vbCrLf & vbCrLf & _
sPostData & vbCrLf & _
"--" & STR_BOUNDARY & "--"
With CreateObject("Microsoft.XMLHTTP")
.Open "POST", uploadDocUrl, bAsync
.SetRequestHeader "Content-Type", "multipart/form-data"
.SetRequestHeader "token", "78bea912b4a5c497b85926bb471fab04"
.Send pvToByteArray(sPostData)
MsgBox (.responseText)
End With
Private Function pvToByteArray(sText As String) As Byte()
pvToByteArray = StrConv(sText, vbUnicode)
End Function

Related

How to handle server address not resolved in XMLHTTP request?

I used the following code to check if a RSS url responds in 5 seconds so I can consume the RSS feed however trying to open the URL causes error when the target URL could not be resolved. What more I need rather than waitForResponse to also handle this situation?
Set http = Server.CreateObject("MSXML2.ServerXMLHTTP")
http.open "POST", "https://persiadigest.com/fa/rss/8", True
http.send
If http.waitForResponse(5) Then
body=http.responsetext
Else
response.write "Target url is not responding"
End If
Set http = Nothing
Error details:
msxml3.dll error '80072ee7' The server name or address could not be
resolved
Give a try for this example and tell me the results :
Option Explicit
Dim Title : Title = "Get RSS FEED"
Dim ArrURL : ArrURL = Array("https://persiadigest.com/fa/rss/8","http://khabarfoori.com/rss/mm")
Dim URL
For Each URL in ArrURL
If CheckURL(URL) = "200" Then
MsgBox chr(34) & URL & chr(34) & " ==> is active"& vbCrLF &_
"Status : " & CheckURL(URL),vbInformation,Title
MsgBox GetDataFromURL(URL,"GET",""),vbInformation,Title
Else
MsgBox chr(34) & URL & chr(34) & " ==> is inactive" & vbCrLF &_
"Status : " & CheckURL(URL),vbCritical,Title
End if
Next
'---------------------------------------------------------------------------
Function GetDataFromURL(strURL, strMethod, strPostData)
Dim lngTimeout
Dim strUserAgentString
Dim intSslErrorIgnoreFlags
Dim blnEnableRedirects
Dim blnEnableHttpsToHttpRedirects
Dim strHostOverride
Dim strLogin
Dim strPassword
Dim strResponseText
Dim objWinHttp
lngTimeout = 59000
strUserAgentString = "http_requester/0.1"
intSslErrorIgnoreFlags = 13056 ' 13056: ignore all err, 0: accept no err
blnEnableRedirects = True
blnEnableHttpsToHttpRedirects = True
strHostOverride = ""
strLogin = ""
strPassword = ""
Set objWinHttp = CreateObject("WinHttp.WinHttpRequest.5.1")
objWinHttp.SetTimeouts lngTimeout, lngTimeout, lngTimeout, lngTimeout
objWinHttp.Open strMethod, strURL
If strMethod = "POST" Then
objWinHttp.setRequestHeader "Content-type", _
"application/x-www-form-urlencoded"
End If
If strHostOverride <> "" Then
objWinHttp.SetRequestHeader "Host", strHostOverride
End If
objWinHttp.Option(0) = strUserAgentString
objWinHttp.Option(4) = intSslErrorIgnoreFlags
objWinHttp.Option(6) = blnEnableRedirects
objWinHttp.Option(12) = blnEnableHttpsToHttpRedirects
If (strLogin <> "") And (strPassword <> "") Then
objWinHttp.SetCredentials strLogin, strPassword, 0
End If
On Error Resume Next
objWinHttp.Send(strPostData)
If Err.Number = 0 Then
If objWinHttp.Status = "200" Then
GetDataFromURL = objWinHttp.ResponseText
Else
GetDataFromURL = "HTTP " & objWinHttp.Status & " " & _
objWinHttp.StatusText
End If
Else
GetDataFromURL = "Error " & Err.Number & " " & Err.Source & " " & _
Err.Description
End If
On Error GoTo 0
Set objWinHttp = Nothing
End Function
'---------------------------------------------------------------------------
Function CheckURL(vURL)
On Error Resume Next
Dim xhr
Set xhr = CreateObject("MSXML2.ServerXMLHTTP.3.0")
xhr.Open "HEAD", vURL, false
xhr.Send
If Err.Number = 0 Then
'MsgBox xhr.status
CheckURL = xhr.status
Else
CheckURL = Err.Description
End If
End Function
'---------------------------------------------------------------------------
A simple function that ignores errors would work.
Function WaitIgnoreError(ByRef requestObject, timeout)
On Error Resume Next
WaitIgnoreError = requestObject.WaitForResponse(timeout)
End Function
Usage:
If WaitIgnoreError(http, 5) Then
body = http.responsetext
Else
response.write "Target url is not responding"
End If

Adding RecordID in front of copied file

I have a code that copies a file from one location to another. What I would like it that when the file is copied, the recordID is placed in front of the file name (example: 150-FirstName). Here is the code I'm working with:
Private Sub cmd_LocateFile_Click()
On Error GoTo Error_Handler
Dim sFile As String
Dim sFolder As String
sFile = FSBrowse("", msoFileDialogFilePicker, "All Files (*.*),*.*")
If sFile <> "" Then
sFolder = Application.CodeProject.path & "\" & sAttachmentFolderName & "\"
If FolderExist(sFolder) = False Then MkDir (sFolder)
If CopyFile(sFile, sFolder & GetFileName(sFile)) = True Then
Me.FullFileName = sFolder & GetFileName(sFile)
Else
End If
End If
Error_Handler_Exit:
On Error Resume Next
Exit Sub
Error_Handler:
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: " & sModName & "\cmd_LocateFile_Click" & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Sub
Try with:
Dim Id As Long
Dim sTarget As String
Id = YourRecordID ' Set current record id.
sTarget = sFolder & CStr(Id) & "-" & GetFileName(sFile)
' Replace your current If-Then-Else-End If block.
If CopyFile(sFile, sTarget)) = True Then
Me!FullFileName.Value = sTarget
End If

mapdrives script use username and password

I am trying to use a VBScript to map network drives. The script is working just fine, except when I am trying to modified it in order to use different credentials (username and password).
Option Explicit
Dim WSHNetwork, strMsg, sUser, sPass
sUser = "user12"
sPass = "testpassword"
Set WSHNetwork = WScript.CreateObject( "WScript.Network")
Call Unmap
Call TryMapDrive("N", "\\192.168.0.10\Music")
Call TryMapDrive("M", "\\192.168.0.10\Movies")
Call TryMapDrive("P", "\\192.168.0.10\Pictures")
Call TryMapDrive("W", "\\192.168.0.10\Work")
Call TryMapDrive("S", "\\192.168.0.10\Store")
strMsg = ShowNetwork() + vbCrLf + vbCrLf + EnumNetworkDrives()
MsgBox strMsg, vbInformation + vbOKOnly, "Network Properties"
Function TryMapDrive(cDrive, strShare, sUser, sPass)
On Error Resume Next
WSHNetwork.MapNetworkDrive cDrive & ":", strShare, sUser, sPass
TryMapDrive = Err.Number = 0
End Function
Function ShowNetwork
Dim strMsg
strMsg = "UserName" & Chr(9) & "= " & WSHNetwork.UserName & vbCrLf & _
"ComputerName" & Chr(9) & "= " & WSHNetwork.ComputerName
ShowNetwork = strMsg
End Function
Function EnumNetworkDrives
Dim colDrives, strMsg, i
Set colDrives = WSHNetwork.EnumNetworkDrives
strMsg = "Current network drive connections: " & vbCrLf
For i = 0 To colDrives.Count - 1 Step 2
strMsg = strMsg & vbCRLF & colDrives(i) & Chr(9) & colDrives(i+1)
Next
EnumNetworkDrives = strMsg
End Function
Function Unmap
On Error Resume Next
Dim objNetwork, colDrives, i
Set objNetwork = CreateObject("WScript.Network")
Set colDrives = objNetwork.EnumNetworkDrives
For i = 0 To colDrives.Count -1 Step 2
objNetwork.RemoveNetworkDrive colDrives.Item(i)
Next
End Function
When I am trying to start it with sPass and sUser it fails with the message below. Without trying different credentials, the script is working fine.

VB6 To send a Form Post

Here is the code I am using:
Dim httpReq As New WinHttp.WinHttpRequest
Dim strLineOut As String
Dim strReturn As String
Dim strStatus As String
lblResponse1.Caption = ""
DoEvents
strLineOut = "<form name=""form1"" method=""post"" enctype=""multipart/form-data"">" & vbCrLf
strLineOut = strLineOut & " <input name=""hdntype"" type=""hidden"" id=""hnd1"" value=""1"">" & vbCrLf
strLineOut = strLineOut & " <input name=""hnd1"" type=""hidden"" id=""hnd1"" value=""Value1"">" & vbCrLf
strLineOut = strLineOut & " <input name=""hdn2"" type=""hidden"" id=""hdn2"" value=""Value2"">" & vbCrLf
strLineOut = strLineOut & " <input type=""submit"" name=""Submit"" value=""Submit"">" & vbCrLf
strLineOut = strLineOut & "</form>" & vbCrLf
httpReq.Open "POST", "http://www.XXXX.com/XMLProjects/vb6test/form_post.asp", False
httpReq.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
'text/xml
'application/x-www-form-urlencoded
'httpReq.StatusText
'httpReq.Status
'httpReq.SetRequestHeader "Content-Length", Len(strLineOut)
httpReq.Send (strLineOut)
strStatus = httpReq.StatusText
strReturn = httpReq.ResponseText
Debug.Print strReturn & vbCrLf & strStatus
lblResponse1.Caption = strReturn & vbCrLf & strStatus
Set httpReq = Nothing
The asp that catches the form cannot seem to recognize the form. It sees a form with one item.
The catch code in the asp is:
Response.Write Request.Form("hdntype")
Response.Write "the form object is " & Request.Form.Item(1) & vbCrLf
The response from the asp is:
the form object is "form1"method="post"enctype="multipart/form-data">
<inputname="hdntype"type="hidden"id="hnd1"value="1">
<inputname="hnd1"type="hidden"id="hnd1"value="Nick">
<inputname="hdn2"type="hidden"id="hdn2"value="Arnone">
<inputtype="submit"name="Submit"value="Submit"></form>
It does not see the item hdntype, or any other item within the form. It sees 1 item, the entire form.
If I do a Request.TotalBytes, I can see everythinhg in the asp.
If I add a querystring objects, I can see each object.
I cannot see form objects.
In VB6, if you send the data like this:
strIDJob = "34"
strAuthString = "supertest"
DataToPost = ""
DataToPost = DataToPost & "IDJob=" & strIDJob & "&"
DataToPost = DataToPost & "AUTH=" & strAuthString & "&"
(im sending it to an ASP page, using the CreateObject("Msxml2.XMLHTTP.6.0") component)
(sending with POST with only this header included: "application/x-www-form-urlencoded")
Then, you can retrieve each item using the code bellow (in ASP), one by one:
IDJob = Request.Form.Item(1) 'here is the core point of this post. This is the line that matters
AUTH = Request.Form.Item(2) 'here is the core point of this post. This is the line that matters
response.write "IDJob = " & IDJob & "<BR>"
response.write "AUTH = " & AUTH & "<BR>"
Response.End
this code in asp produces the following return/output:
IDJob = 34AUTH = supertest

How to have app automatically send log file to support?

In order to manage the errors coming from a particular client I am thinking about having the app send the current error log file to me, perhaps when it starts up.
What would the best way to achieve this in a VB6/XP environment?
Email might be easy but I imagine that could fire off all sorts of anti-virus/firewall protections.
Connecting to a webserver might be better. Would the app still have to open up the Windows firewall in this case?
I'm using XMLHTTP to upload clients error logs like this: http://wqweto.wordpress.com/2011/07/12/vb6-using-wininet-to-post-binary-file/
Private Sub pvPostFile(sUrl As String, sFileName As String, Optional ByVal bAsync As Boolean)
Const STR_BOUNDARY As String = "3fbd04f5-b1ed-4060-99b9-fca7ff59c113"
Dim nFile As Integer
Dim baBuffer() As Byte
Dim sPostData As String
'--- read file
nFile = FreeFile
Open sFileName For Binary Access Read As nFile
If LOF(nFile) > 0 Then
ReDim baBuffer(0 To LOF(nFile) - 1) As Byte
Get nFile, , baBuffer
sPostData = StrConv(baBuffer, vbUnicode)
End If
Close nFile
'--- prepare body
sPostData = "--" & STR_BOUNDARY & vbCrLf & _
"Content-Disposition: form-data; name=""uploadfile""; filename=""" & Mid$(sFileName, InStrRev(sFileName, "\") + 1) & """" & vbCrLf & _
"Content-Type: application/octet-stream" & vbCrLf & vbCrLf & _
sPostData & vbCrLf & _
"--" & STR_BOUNDARY & "--"
'--- post
With CreateObject("Microsoft.XMLHTTP")
.Open "POST", sUrl, bAsync
.SetRequestHeader "Content-Type", "multipart/form-data; boundary=" & STR_BOUNDARY
.Send pvToByteArray(sPostData)
End With
End Sub
Private Function pvToByteArray(sText As String) As Byte()
pvToByteArray = StrConv(sText, vbFromUnicode)
End Function

Resources