Jump to content
Sign in to follow this  
AlmarM

Need help sending an image to a PHP file using WinHTTP

Recommended Posts

AlmarM

Hello,

For sharing screenshots with my friends I'm using uploadscreenshot.com.

I noticed they have a useable API, so I thought I could create a neat little program which will upload screenshot with a single button click.

After reading their documentation I started to play some with WinHTTP, but unfortunately I have zero experience with WinHTTP.

API documentation: www.uploadscreenshot.com/api-documentation

What I've tried:

#include "WinHTTP/WinHttp.au3"

Global Const $sAPIKey = "*snip*"
Global Const $sAPIURL = "http://img1.uploadscreenshot.com/api-upload.php"
Global Const $sIP = "209.105.243.66" ; pinged from 'uploadscreenshot.com'

Global $hOpen = _WinHttpOpen()
Global $hConnect = _WinHttpConnect($hOpen, $sAPIURL)
Global $hRequest = _WinHttpOpenRequest($hConnect, "POST", "C:\Users\Lyker\Desktop\Other\Untitled-1.png")

_WinHttpSendRequest($hRequest)
_WinHttpReceiveResponse($hRequest)

MsgBox(0, "", _WinHttpReadData($hRequest))

_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)

I have no idea how I should use the WinHTTP UDF to connect with their API and send images & fill in variables. ;)

Any pokes in the right direction?

Almar

Edited by AlmarM

Minesweeper

A minesweeper game created in autoit, source available.

_Mouse_UDF

An UDF for registering functions to mouse events, made in pure autoit.

2D Hitbox Editor

A 2D hitbox editor for quick creation of 2D sphere and rectangle hitboxes.

Share this post


Link to post
Share on other sites
AlmarM

I've tried some more things and I already got some closer!

#include "WinHTTP/WinHttp.au3"

Global Const $sAPIKey = "81d63021b65545554828638091"
Global Const $sAPIURL = "/api-upload.php?apiKey=" & $sAPIKey & "&xmlOutput=1&testMode=1"
Global Const $sURL = "img1.uploadscreenshot.com"

Global $hOpen = _WinHttpOpen()
Global $hConnect = _WinHttpConnect($hOpen, $sURL)
ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $hConnect = ' & $hConnect & @crlf & '>Error code: ' & @error & @crlf) ;### Debug Console
Global $hRequest = _WinHttpOpenRequest($hConnect, "POST", $sAPIURL)

_WinHttpSendRequest($hRequest)
_WinHttpWriteData($hRequest, StringToBinary(FileRead("C:UsersLykerDesktopOtherUntitled-1.png")))
_WinHttpReceiveResponse($hRequest)

MsgBox(0, "", _WinHttpReadData($hRequest))

_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)

It now returns what it should return.

The only problem now is that I don't know how to send the image using POST to that PHP file.

The XML is giving me a ERRORCODE=6. Which means the 'userfile' is empty, AKA I did not send the image correctly.

Anyone? ;)


Minesweeper

A minesweeper game created in autoit, source available.

_Mouse_UDF

An UDF for registering functions to mouse events, made in pure autoit.

2D Hitbox Editor

A 2D hitbox editor for quick creation of 2D sphere and rectangle hitboxes.

Share this post


Link to post
Share on other sites
Tankbuster

During your second post I tried something simliar but with the same result.

I tried their docu on the api....and the demo html post:

http://uploadscreenshot.com/api/test-api.html

I noticed when I select a image with a path (and the path is shown in the formular) the post message does not got the path

http://img1.uploadscreenshot.com/api-upload.php?userfile=Desert.jpg&apiKey=519acd4be68445997245348820&xmlOutput=1&imageMD5=&username=&userPasswordMD5=&testMode=1&Submit=Upload

I' not that much experienced, but it looks like the post does not take care about paths....

Sorry, not helping you. Maybe search for "POST File with path"?

Share this post


Link to post
Share on other sites
AlmarM

I've found something in the WinHTTP UDF post (from trancexx) in example scripts by ProgAndy.

I think that is what I need, but with my little expierence I think I cannot figure that out alone. ;)

Edited by AlmarM

Minesweeper

A minesweeper game created in autoit, source available.

_Mouse_UDF

An UDF for registering functions to mouse events, made in pure autoit.

2D Hitbox Editor

A 2D hitbox editor for quick creation of 2D sphere and rectangle hitboxes.

Share this post


Link to post
Share on other sites
AlmarM

You left your key in pal

I saw, but it doesn't matter.

You can register multiple API key's on the same e-mail, uploadscreenshot.com doesn't care about that. :)

What if I forget my API key?

Just register for a new one above.

Can I request multiple API keys for the same email address?

Yes, just submit the form as many times as needed and a new key will be sent each time. This way you can use a different API key in each of your applications.

Thanks though! ;)

EDIT:

God this is hard..

My next try:

#include "WinHTTP/WinHttp.au3"

Global Const $sAPIKey = "81d63021b65545554828638091"
Global Const $sAPIURL = "/api-upload.php?apiKey=" & $sAPIKey & "&xmlOutput=1&testMode=1"
Global Const $sURL = "img1.uploadscreenshot.com"

Global $hOpen = _WinHttpOpen()
Global $hConnect = _WinHttpConnect($hOpen, $sURL)
Global $hRequest = _WinHttpOpenRequest($hConnect, "POST", $sAPIURL)

Global $sData = ""
$sData = 'MIME-Version: 1.0' & @CRLF
$sData &= 'Content-Type: multipart/mixed; boundary=darker' & @CRLF & @CRLF ; on or off? since it's already givin inside the _WinHttpSendRequest
$sData &= '--darker' & @CRLF
$sData &= 'Content-Disposition: attachment; filename="Untitled-1.png"' & @CRLF
$sData &= 'Content-Type: image/png' & @CRLF & @CRLF
$sData &= FileRead("C:UsersLykerDesktopOtherUntitled-1.png") & @CRLF ;~ $sData &= _Base64Encode(FileRead("C:UsersLykerDesktopOtherUntitled-1.png")) & @CRLF
$sData &= '--darker--'

FileWrite(@DesktopDir & "asdas.txt", $sData)
_WinHttpSendRequest($hRequest, "Content-Type: multipart/mixed; boundary=darker", $WINHTTP_NO_REQUEST_DATA, StringLen($sData))
;~ _WinHttpWriteData($hRequest, $sData)
_WinHttpWriteDataBin($hRequest, StringToBinary($sData)) ; base 64 encode or binary send?
_WinHttpReceiveResponse($hRequest)

MsgBox(0, "", _WinHttpReadData($hRequest))

_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)

Func _WinHttpWriteDataBin($hRequest, $bBinary)
    Local $lpBinary
    Local $iNumberOfBytesToWrite
    If IsDllStruct($bBinary) Then
        $lpBinary = DllStructGetPtr($bBinary)
        $iNumberOfBytesToWrite = DllStructGetSize($bBinary)
    Else
        $iNumberOfBytesToWrite = BinaryLen($bBinary)
        Local $sBinary = DllStructCreate("byte[" & $iNumberOfBytesToWrite & "]")
        DllStructSetData($sBinary, 1, $bBinary)
        $lpBinary = DllStructGetPtr($sBinary)
    EndIf

    Local $a_iCall = DllCall("Winhttp.dll", "int", "WinHttpWriteData", _
            "hwnd", $hRequest, _
            "ptr", $lpBinary, _
            "dword", $iNumberOfBytesToWrite, _
            "dword*", 0)

    If @error Or Not $a_iCall[0] Then
        Return SetError(1, 0, 0)
    EndIf

    Return SetError(0, $a_iCall[4], 1)
EndFunc

Func _Base64Encode($sData)
    Local $oXml = ObjCreate("Msxml2.DOMDocument")
    If Not IsObj($oXml) Then
        SetError(1, 1, 0)
    EndIf

    Local $oElement = $oXml.createElement("b64")
    If Not IsObj($oElement) Then
        SetError(2, 2, 0)
    EndIf

    $oElement.dataType = "bin.base64"
    $oElement.nodeTypedValue = Binary($sData)
    Local $sReturn = $oElement.Text

    If StringLen($sReturn) = 0 Then
        SetError(3, 3, 0)
    EndIf

    Return $sReturn
EndFunc   ;==>_Base64Encode
Edited by AlmarM

Minesweeper

A minesweeper game created in autoit, source available.

_Mouse_UDF

An UDF for registering functions to mouse events, made in pure autoit.

2D Hitbox Editor

A 2D hitbox editor for quick creation of 2D sphere and rectangle hitboxes.

Share this post


Link to post
Share on other sites
trancexx

It should be something like this:

#include "WinHTTP/WinHttp.au3"

Global $sFile = "C:UsersLykerDesktopOtherUntitled-1.png"

Global Const $sAPIKey = "81d63021b65545554828638091"
Global Const $sURL = "uploadscreenshot.com"

; Session
Global $hOpen = _WinHttpOpen()
; Connection
Global $hConnect = _WinHttpConnect($hOpen, $sURL)

; Upload image
Global $sRead = _WinHttpSimpleFormFill($hConnect, "api/test-api.html", Default, _
        "apiKey", $sAPIKey, _
        "xmlOutput", 1, _
        "testMode", 1, _
        "name:userfile", $sFile)

; Close connection handle
_WinHttpCloseHandle($hConnect)
; Close session handle
_WinHttpCloseHandle($hOpen)

ConsoleWrite($sRead & @CRLF)

; Bye, bye...

WinHttp has its own help file. Use it.

  • Like 1

♡♡♡

.

eMyvnE

Share this post


Link to post
Share on other sites
ProgAndy

Here is a complete example without using the HTML form:

#include "Z:/daten/Dokumente/AutoIt3/UDF/WinHttp.au3"
#include <Crypt.au3>

Global Const $fTestMode = True ; testmode will delete images after 15 minutes
Global Const $sAPIKey = "519acd4be68445997245348820" ; testkey, images will always be deleted after 15 minutes
Global Const $sAPIURL = "/api-upload.php"
Global Const $sURL = "img1.uploadscreenshot.com"

Global $hOpen = _WinHttpOpen("AutoIt UploadScreenShot Demo v1")
Global $hConnect = _WinHttpConnect($hOpen, $sURL)
Global $hRequest = _WinHttpOpenRequest($hConnect, "POST", $sAPIURL)

Global $sData = ""
If $fTestMode Then
    $sData &= '----------darker' & @CRLF
    $sData &= 'Content-Disposition: form-data; name="testMode"' & @CRLF & @CRLF
    $sData &= '1' & @CRLF
EndIf
$sData &= '----------darker' & @CRLF
$sData &= 'Content-Disposition: form-data; name="xmlOutput"' & @CRLF & @CRLF
$sData &= '1' & @CRLF
$sData &= '----------darker' & @CRLF
$sData &= 'Content-Disposition: form-data; name="imageMD5"' & @CRLF & @CRLF
$sData &= StringLower(Hex(_Crypt_HashFile(@ScriptDir & "testimage.png", $CALG_MD5))) & @CRLF
$sData &= '----------darker' & @CRLF
$sData &= 'Content-Disposition: form-data; name="userfile"; filename="testimage.png"' & @CRLF
$sData &= 'Content-Type: image/png' & @CRLF & @CRLF
$sData &= FileRead(@ScriptDir & "testimage.png") & @CRLF ;~ $sData &= _Base64Encode(FileRead("C:UsersLykerDesktopOtherUntitled-1.png")) & @CRLF
$sData &= '----------darker--'

_WinHttpSendRequest($hRequest, "Content-Type: multipart/form-data; boundary=--------darker", Binary($sData))
_WinHttpReceiveResponse($hRequest)

$sResult = _WinHttpReadData($hRequest)
MsgBox(0, "", $sResult)
ConsoleWrite($sResult & @CRLF)

_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)
  • Like 1

*GERMAN* [note: you are not allowed to remove author / modified info from my UDFs]My UDFs:[_SetImageBinaryToCtrl] [_TaskDialog] [AutoItObject] [Animated GIF (GDI+)] [ClipPut for Image] [FreeImage] [GDI32 UDFs] [GDIPlus Progressbar] [Hotkey-Selector] [Multiline Inputbox] [MySQL without ODBC] [RichEdit UDFs] [SpeechAPI Example] [WinHTTP]UDFs included in AutoIt: FTP_Ex (as FTPEx), _WinAPI_SetLayeredWindowAttributes

Share this post


Link to post
Share on other sites
AlmarM

Awe-some work, both samples work like a charm! ;)

I personally don't like filling in forms, so I'll use ProgAndy's sample.

But I've learned a lot from both samples. Thanks!


Minesweeper

A minesweeper game created in autoit, source available.

_Mouse_UDF

An UDF for registering functions to mouse events, made in pure autoit.

2D Hitbox Editor

A 2D hitbox editor for quick creation of 2D sphere and rectangle hitboxes.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Similar Content

    • Surya
      By Surya
      Hi everyone its been loooong since I posted here 
      I have been trying to convert this curl executable parameters into autoit using the winhttp com object;
      curl -F data_file=@my_audio_file.mp3 -F model=en-US "https://api.speechmatics.com/v1.0/user/41049/jobs/?auth_token=MmQ5MTk4jdsgjhgghstOGU5YS00OWFhLWghdgjshgdhbshj017###" any ideas guys
       
      PS: I am excited to post here after a looong time
    • Ascer
      By Ascer
      Hello
      Opertation Sys: Win7 x64
      Problem: Connecting to webs using TLS 1.1 +
      Description: WinHttp.WinHttpRequest.5.1 using TLS 1.0 by default, i need higher version to connect into some webs.
      Dim $oHttp = ObjCreate("WinHTTP.WinHTTPRequest.5.1") $oHttp.open ("GET", "https://howsmyssl.com/a/check", False) $oHttp.Option(9) = 128 ; 128 - TLS 1.0, 512 - TLS 1.1, 2048 - TLS 1.2, 2056 - TLS 1.1 & TLS 1.2 $oHttp.Send ConsoleWrite($oHttp.responseText & @CRLF) ; at end of the respond you can check your TLS version. Mine is: {"tls_version":"TLS 1.0","rating":"Bad"} Error: $oHttp.Option works only with parameter 128 (TLS 1.0) other values make error {Bad parameter}
      Additional: I've done this tutorial about enabling TLS in registry: <link>
      Thanks for support.
      Ascer
    • islandspapand
      By islandspapand
      Hi All
      i am currently trying to add a function to my project that can send SMS, i have gone with Twilio for the sms service that use a REST API.
      I have never worked with an API before, and could use some help.
      I can get my function working with using cURL.exe and copy past command from the website with the following code. And thats great unfortunately i am have issue with character like æøå when sending a SMS appears like a box or ?. this does not happen if i do it from the website so it looks like a Unicode issue in curl.exe.
      I have done some searching on the forum and understand that i should be able to implement this curl command with the WinHTTP UDF from @trancexx so i don't need a third part exe and it might fix my charater issue.
      Unfortunately i really don't understand how i am to change curl commands to the WinHTTP and i was hoping some good maybe give me an example i could learn from.
      Thanks in advanced
      i have removed the AuthToken number from the script.
      _SendSMS("00000000","SomeOne","SMS body info") Func _SendSMS($SendTo,$SendFrom,$Msgtxt) $AccountSID = "ACbb765b3180d5938229eff8b8f63ed1bc" $AuthToken = "Auth Token number" $Data = '"https://api.twilio.com/2010-04-01/Accounts/'&$AccountSID&'/Messages.json"'& _ '-X POST \ --data-urlencode "To=+45'&$SendTo&'" \ --data-urlencode "From='&$SendFrom&'" \ --data-urlencode "Body='&$Msgtxt&'" \ -u '&$AccountSID&':'&$AuthToken&'' ShellExecute(@ScriptDir&"\curl.exe","-k "&$Data) ;~ curl 'https://api.twilio.com/2010-04-01/Accounts/ACbb765b3180d5938229eff8b8f63ed1bc/Messages.json' -X POST \ ;~ --data-urlencode 'To=+4500000000' \ ;~ --data-urlencode 'From=Reception' \ ;~ --data-urlencode 'Body=Test Body' \ ;~ -u ACbb765b3180d5938229eff8b8f63ed1bc:[AuthToken] EndFunc  
       
    • jesus40
      By jesus40
      Hello friends, i have a working curl command that show informations about my account on binance.com, but_it dont work with autoit code without curl.exe.
      I want to do it without curl, because the whole process much Slower_ with StdoutRead (I want get the response in variable.)
      My Curl command in Autoit:
      This 2 are works, but_ i would like to do it without curl.exe
      $apikey="XYZ" sCommand = @ScriptDir & '\curl.exe -k -H "X-MBX-APIKEY: ' & $apikey & '" -X GET "https://api.binance.com/api/v3/account?' & $request the same in .bat  file
      curl.exe -k -H "X-MBX-APIKEY: XYZ" -X GET "https://api.binance.com/api/v3/account?timestamp=1514917812000&signature=85bdee77e53cd521e1d5229fbfb459d53799c42b3fa4596d73f1520fad5f965a" (I use curl with -k option which allows curl to make insecure connections, because there is problem with the sites certificate, (cURL error 60))
       
      I tried many variations, this is the latest... I cant get the same response.
      curl $error message (I changed ): {"code":-2015,"msg":"Invalid API-key, IP, or permissions for action."}
      autoit version $error message (Response code:400): Mandatory parameter 'timestamp' was not sent, was empty/null, or malformed.
       
      $request = $query & '&signature=' & $signature $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") $oHTTP.Open("GET", "https://api.binance.com/api/v3/account", False) $oHTTP.SetRequestHeader("X-MBX-APIKEY", $apikey) $oHTTP.Send($request) $oReceived = $oHTTP.ResponseText $oStatusCode = $oHTTP.Status If $oStatusCode <> 200 then MsgBox(4096, "Response code", $oStatusCode) EndIf  
      thanks
    • AlwaysLearning
      By AlwaysLearning
      Hello,
      I have been struggling with this for nearly 20 hours, and I just cannot seem to figure out the formatting for the header request.
      To test this, you will need to use this api key I set up for your testing purposes. (note, I sent tracexx a direct message about this as I didn't realize I could limit API restrictions until just now, so I am now hoping on of you may have the answer on hand)
      I need to be able to GET balance and POST orders.
      Right now, I can't get past the 401/403 errors on my own.
      I believe the Content is formatted for JSON, but using the JSON format didn't work for me ( although that may be because I'm an idiot and formatted something wrong).
      I want to get:
      GET balance page POST delete order page Here is a temporary API key + Secret API key with only the "View Balance Page" and "Delete Order" functions enabled:
      Access-key: tq6GeUrEvfxyF-LG
      Secret Access-Key: cZlz75K1wb8-Ed67pRaXvUWTPW6RTH9q

      Here is the site's API guide (I followed this closely and doubt the error is there): https://coincheck.com/documents/exchange/api#libraries
       
      And here is running source code (needs those keys inputted) which will hash the above keys to the required HMAC SHA256:
      #include <Crypt.au3> #include<WinHttp.au3> Global Const $CALG_SHA_256 = 0x0000800c ;; ===== $api = "/api/accounts/balance" $accessNonCE = _TimeGetStamp() $url = "https://coincheck.com/api/accounts/balance" $body = "" WinHTTP($url, $body) Func WinHTTP($sUrl, $sBody) Local $hOpen = _WinHttpOpen() Local $hConnect = _WinHttpConnect($hOpen, "https://coincheck.com/api/accounts/balance") ; Specify the reguest: ;Local $hRequest = _WinHttpOpenRequest($hConnect, Default, $sApi) $accessKey = "" ;; Add the key from above $secretKey = "" ;; Add the secret key from above $message = $accessNonCE & $sUrl $BinarySignature = HMAC($secretKey, $message) $signature = _Base64Encode($BinarySignature) ;Encode signature Local $hRequest = _WinHttpOpenRequest($hConnect, "GET") _WinHttpAddRequestHeaders($hRequest, 'ACCESS-KEY: '&$accessKey) _WinHttpAddRequestHeaders($hRequest, 'ACCESS-NONCE: '&$accessNonCE) _WinHttpAddRequestHeaders($hRequest, 'ACCESS-SIGNATURE: '&$signature) ; Send request _WinHttpSendRequest($hRequest) ; Wait for the response _WinHttpReceiveResponse($hRequest) Local $sHeader = _WinHttpQueryHeaders($hRequest) ; ...get full header Local $sData = _WinHttpReadData($hRequest) ; Clean _WinHttpCloseHandle($hRequest) _WinHttpCloseHandle($hConnect) _WinHttpCloseHandle($hOpen) ; Display retrieved data MsgBox(0, "Data", $sData) EndFunc Func sha256($message) Return _Crypt_HashData($message, $CALG_SHA_256) EndFunc Func HMAC($key, $message, $hash="sha256") Local $blocksize = 64 Local $a_opad[$blocksize], $a_ipad[$blocksize] Local Const $oconst = 0x5C, $iconst = 0x36 Local $opad = Binary(''), $ipad = Binary('') $key = Binary($key) If BinaryLen($key) > $blocksize Then $key = Call($hash, $key) For $i = 1 To BinaryLen($key) $a_ipad[$i-1] = Number(BinaryMid($key, $i, 1)) $a_opad[$i-1] = Number(BinaryMid($key, $i, 1)) Next For $i = 0 To $blocksize - 1 $a_opad[$i] = BitXOR($a_opad[$i], $oconst) $a_ipad[$i] = BitXOR($a_ipad[$i], $iconst) Next For $i = 0 To $blocksize - 1 $ipad &= Binary('0x' & Hex($a_ipad[$i],2)) $opad &= Binary('0x' & Hex($a_opad[$i],2)) Next Return Call($hash, $opad & Call($hash, $ipad & Binary($message))) EndFunc Func _TimeGetStamp() Local $av_Time $av_Time = DllCall('CrtDll.dll', 'long:cdecl', 'time', 'ptr', 0) If @error Then SetError(99) Return False EndIf Return $av_Time[0] EndFunc Func _Base64Encode($input) $input = Binary($input) Local $struct = DllStructCreate("byte[" & BinaryLen($input) & "]") DllStructSetData($struct, 1, $input) Local $strc = DllStructCreate("int") Local $a_Call = DllCall("Crypt32.dll", "int", "CryptBinaryToString", _ "ptr", DllStructGetPtr($struct), _ "int", DllStructGetSize($struct), _ "int", 1, _ "ptr", 0, _ "ptr", DllStructGetPtr($strc)) If @error Or Not $a_Call[0] Then Return SetError(1, 0, "") ; error calculating the length of the buffer needed EndIf Local $a = DllStructCreate("char[" & DllStructGetData($strc, 1) & "]") $a_Call = DllCall("Crypt32.dll", "int", "CryptBinaryToString", _ "ptr", DllStructGetPtr($struct), _ "int", DllStructGetSize($struct), _ "int", 1, _ "ptr", DllStructGetPtr($a), _ "ptr", DllStructGetPtr($strc)) If @error Or Not $a_Call[0] Then Return SetError(2, 0, ""); error encoding EndIf Return DllStructGetData($a, 1) EndFunc ;==>_Base64Encode
       
×