Sign in to follow this  
Followers 0
AlmarM

Need help sending an image to a PHP file using WinHTTP

9 posts in this topic

#1 ·  Posted (edited)

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



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

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

#4 ·  Posted (edited)

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

#6 ·  Posted (edited)

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

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.

1 person likes this

♡♡♡

.

eMyvnE

Share this post


Link to post
Share on other sites

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)
1 person likes this

*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

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  
Followers 0

  • Similar Content

    • nhardel
      By nhardel
      I have been working on trying to develop some scripts to interface with the REST/JSON API from the Orion SDK.  This is where I will ask my questions and hopefully get some community responses that could help benefit others. 
      https://github.com/solarwinds/OrionSDK
      I am trying to create examples of how to interface with the API from autoit.  This should be a knowledge dump for this task. 
    • n3wbie
      By n3wbie
      How to send Requests on https Website
      I tried using
      ObjCreate("winhttp.winhttprequest.5.1")
      But m not Receiving Any response
      m able to retrive https://google.com but same is not available on other site( https://gst.gov.in )
      kindly help me
    • nhardel
      By nhardel
      So I have been bashing my head in for a couple days and have searched both AutoIT forums and Thwack Forums for an answer.  I understand this could be hard to help sense I can't provide a server for someone to help me test against.  I am trying to use the WinHTTP.au3 to connect with Solarwinds Orion SDK thru REST/JSON api calls.  Here is the documentation that they provide.
      https://github.com/solarwinds/OrionSDK/wiki/REST
      I have been trying just to make a basic connection but for some reason cannot get past the authorization process with WinHTTP.  Here is my test code.
      #Region Includes #include <log4a.au3> #include "WinHttp.au3" #EndRegion Global $sAddress = "https://usandl0213:17778/SolarWinds/InformationService/v3/Json/Query?query=SELECT+NodeID+FROM+Orion.NODES" Global $array_URL = _WinHttpCrackUrl($sAddress) ;~ Row|Col 0 ;~ [0]|https ;~ [1]|2 ;~ [2]|usandl0213 ;~ [3]|17778 ;~ [4]| ;~ [5]| ;~ [6]|/SolarWinds/InformationService/v3/Json/Query ;~ [7]|?query=SELECT+NodeID+FROM+Orion.NODES Global $hOpen = _winhttpOpen() If @error Then _log4a_Fatal("Error intializing the usage of WinHTTP functions") Exit 1 EndIf Global $hConnect = _winhttpConnect($hOpen, $array_URL[2]) If @error Then _log4a_Fatal("Error specifying the initial target server of an HTTP request.") _WinHttpCloseHandle($hOpen) Exit 2 EndIf Global $hRequest = _WinHttpOpenRequest($hConnect, _ "GET", _ "/SolarWinds/InformationService/v3/Json/Query?query=SELECT+NodeID+FROM+Orion.NODES", _ "HTTP/1.1") If @error Then _log4a_Fatal(MsgBox(48, "Error", "Error creating an HTTP request handle.") _WinHttpCloseHandle($hConnect) _WinHttpCloseHandle($hOpen) Exit 3 EndIf _WinHttpAddRequestHeaders($hRequest, "Authorization: Basic YXV0b2l0X2xvZ2luOnRlc3Q=") _WinHttpAddRequestHeaders($hRequest, "User-Agent: curl/7.20.0 (i386-pc-win32) libcurl/7.20.0 OpenSSL/0.9.8l zlib/1.2.3") _WinHttpAddRequestHeaders($hRequest, "Host: usandl0213:17778") _WinHttpAddRequestHeaders($hRequest, "Accept: */*") _WinHttpSendRequest($hRequest) If @error Then MsgBox(48, "Error", "Error sending specified request.") Close_request() Exit 4 EndIf ; Wait for the response _WinHttpReceiveResponse($hRequest) If @error Then MsgBox(48, "Error", "Error waiting for the response from the server.") Close_request() Exit 5 EndIf Global $sChunk, $sData ; See what's returned If _WinHttpQueryDataAvailable($hRequest) Then Global $sHeader = _WinHttpQueryHeaders($hRequest) ;~ ConsoleWrite(@crlf) ConsoleWrite($sHeader & @CRLF) ; Read While 1 $sChunk = _WinHttpReadData($hRequest) If @error Then ExitLoop $sData &= $sChunk WEnd ConsoleWrite($sData & @CRLF) ; print to console Else MsgBox(48, "Error", "Site is experiencing problems.") EndIf Close_request() Func Close_request() ; Close open handles and exit _WinHttpCloseHandle($hRequest) _WinHttpCloseHandle($hConnect) _WinHttpCloseHandle($hOpen) EndFunc I am definitely connecting to the server but get a 401 Unauthorized response.  Output of above script:
      Header:
      HTTP/1.1 401 Unauthorized Cache-Control: private Date: Thu, 27 Jul 2017 15:31:21 GMT Content-Length: 1668 Content-Type: text/html; charset=utf-8 Server: Microsoft-IIS/7.5 Set-Cookie: ASP.NET_SessionId=lgwin2qsbbrip2mxg01fot05; path=/; HttpOnly Set-Cookie: TestCookieSupport=Supported; path=/ Set-Cookie: Orion_IsSessionExp=TRUE; expires=Thu, 27-Jul-2017 17:31:21 GMT; path=/ WWW-Authenticate: Negotiate WWW-Authenticate: NTLM X-UA-Compatible: IE=9 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET X-Same-Domain: 1 X-Content-Type-Options: nosniff X-Frame-Options: SAMEORIGIN X-XSS-Protection: 1; mode=block Body:
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head><link rel="stylesheet" type="text/css" href="/orion/js/jquery-1.7.1/jquery-ui.css.i18n.ashx?l=en-US&v=42660.90.L&csd=%23b0b9c5;%23d2ddec;%2392add1;" /> <link rel="stylesheet" type="text/css" href="/orion/styles/orionminreqs.css.i18n.ashx?l=en-US&v=42660.90.L&csd=%23b0b9c5;%23d2ddec;%2392add1;" /> <link rel="stylesheet" type="text/css" href="/webengine/resources/steelblue.css.i18n.ashx?l=en-US&v=42660.90.L&csd=%23b0b9c5;%23d2ddec;%2392add1;" /> <link rel="stylesheet" type="text/css" href="/orion/ipam/res/css/sw-events.css.i18n.ashx?l=en-US&v=42660.90.L&csd=%23b0b9c5;%23d2ddec;%2392add1;" /> <script type="text/javascript" src="/orion/js/orionminreqs.js.i18n.ashx?l=en-US&v=42660.90.L"></script> <script type="text/javascript" src="/orion/js/modernizr/modernizr-2.5.3.js.i18n.ashx?l=en-US&v=42660.90.L"></script> <script type="text/javascript" src="/orion/js/jquery-1.7.1/jquery-1.7.1.framework.min.js.i18n.ashx?l=en-US&v=42660.90.L"></script> <script type="text/javascript">(function(){var de=$(document.documentElement); de.addClass('sw-is-locale-en'); $.each(jQuery.browser,function(k,v){if(v===true){ de.addClass('sw-is-'+k); de.addClass('sw-is-'+k+'-'+parseInt(jQuery.browser.version)); }}); })();</script> <script type="text/javascript">SW.Core.Loader._cbLoaded('jquery');</script> <script type="text/javascript">SW.Core.Date._init(0,-14400000);</script> <title> </title></head> <body> <script> window.location = 'Login.aspx'; </script> </body> </html> To me this looks like it if it is still looking for my credentials.   I did verify that things work as expected using Chrome and REST test client.  I do get certificate errors in IE if I try to go directly.  Bypass certificate issues and page will try to save out to .json file
       
      Looking for any help.
    • Jefrey
      By Jefrey
      I've made this HTTP lib to simplify HTTP requests, mainly when dealing about POST data or file uploads.
      Three functions are available:
      string _HTTP_Get ( string $sURL ) string _HTTP_Post ( string $sURL , string $sPostData ) string _HTTP_Upload ( string $sURL , string $sFilePath , string $sFileField , string $sPostData = '' , string $sFilename = Default) Additionaly, two helper functions are also available:
      URLEncode($sStr) URLDecode($sStr) Full documentation: https://github.com/jesobreira/HTTP.au3/blob/master/README.md
      Fork me on Github: https://github.com/jesobreira/HTTP.au3
      Download lib + docs: https://github.com/jesobreira/HTTP.au3/archive/master.zip
    • RyukShini
      By RyukShini
      Hello everyone.
      I would like to automate some things on my forum with AutoIT and so far I successfully logged in and everything seems to be going well, however this type of form I have no clue on how to make, I tried with a couple of different ideas and what not, but so far it wont work.
      I already found what I need for making unix timestamps and so on, so all I need is to understand how to make this in WINHTTP
      $sRead = _WinHttpSimpleFormFill($xConnect, "posting.php?mode=post&f=124", Default, "name:topic_seo_title", "testing my stuff before actually posting", "name:seo_desc", "testing my stuff before actually posting", "name:icon", "2", "name:subject", "testing my stuff before actually posting", "name:addbbcode20", "100", "name:message", "MoonBoys full video rips from popular porn sites", "name:post", "Submit", "name:fileupload", "Content-Type: application/octet-stream", "name:filecomment", "name:lastclick", $iUnixTime, "name:creation_time", $iUnixTime, "name:form_token", $uh) ------WebKitFormBoundaryPH Content-Disposition: form-data; name="topic_seo_title" testing my stuff ------WebKitFormBoundaryPH Content-Disposition: form-data; name="seo_desc" testing my stuff ------WebKitFormBoundaryPH Content-Disposition: form-data; name="seo_key" ------WebKitFormBoundaryPH Content-Disposition: form-data; name="icon" 2 ------WebKitFormBoundaryPH Content-Disposition: form-data; name="subject" testing my stuff ------WebKitFormBoundaryPH Content-Disposition: form-data; name="addbbcode20" 100 ------WebKitFormBoundaryPH Content-Disposition: form-data; name="message" [center][b]testing this[/b] [i][b]test: test: [neon=Pink]Screenshots:[/neon] test Details:[/b][/i][/center] ------WebKitFormBoundaryPH Content-Disposition: form-data; name="post" Submit ------WebKitFormBoundaryPH Content-Disposition: form-data; name="fileupload"; filename="" Content-Type: application/octet-stream ------WebKitFormBoundaryPH Content-Disposition: form-data; name="filecomment" ------WebKitFormBoundaryPH Content-Disposition: form-data; name="lastclick" 1488467908 ------WebKitFormBoundaryPH Content-Disposition: form-data; name="creation_time" 1488467908 ------WebKitFormBoundaryPH Content-Disposition: form-data; name="form_token" 4ee1f6e9f21d7147f31a94d16bb16eaddf7bb3e8 ------WebKitFormBoundaryPHhcKRBLEwtQXIqY--