Jump to content

Upload file


Kolrac
 Share

Recommended Posts

Hi! this is my first message and I have start few week ago to use AutoIt... incredible product but I have now a problem.

I have to send some files - in batch mode - thru the standard http upload (like form upload in multi-part mode... like <input type=file>) but ... I have try to search in the documentation and in the web... nothing... Is possible to do this? how? ... can you help me with some ideas?

tks a lot

Link to comment
Share on other sites

Or maybe use IE.au3 to automate the webpage. Look at the help file under User Defined Functions > IE Management

User Defined Function Reference

Below is a list of the user defined functions for catagory: IE Management.

Click on a user defined function name for a detailed description.

User Defined Function Description

_IE_Example Display a new browser window pre-loaded with documents to be used in IE.au3 examples

_IE_Introduction Display introductory information about IE.au3 in a new browser window

_IE_VersionInfo Returns an array of information about the IE.au3 version

_IEAction Perform any of a set of simply actions on the Browser.

_IEAttach Attach to the first existing instance of Internet Explorer where the search string sub-string matches based on the selected mode.

_IEBodyReadHTML Returns the HTML inside the tag of the document.

_IEBodyReadText Returns the Text inside the tag of the document.

_IEBodyWriteHTML Replaces the HTML inside the tag of the document.

_IECreate Create an Internet Explorer Browser window.

_IECreateEmbedded Create a Webbrowser object suitable for embedding in an AutoIt GUI with GuiCtrlCreateObj().

_IEDocGetObj Given any DOM object, returns a reference to the associated document object.

_IEDocReadHTML Returns the full HTML source of a document.

_IEDocWriteHTML Replaces the HTML for the entire document.

_IEErrorHandlerDeRegister Disable a registered user COM error handler

_IEErrorHandlerRegister Register and enable a user COM error handler

_IEErrorNotify Specifies whether IE.au3 automatically notifies of Warnings and Errors (to the console)

_IEFormElementCheckboxSelect Set the value of a specified form element.

_IEFormElementGetCollection Returns a collection object variable representing all Form Elements within a given Form.

_IEFormElementGetObjByName Returns an object reference to a Form Element by name.

_IEFormElementGetValue Returns the value of a given Form Element.

_IEFormElementOptionselect Set the value of a specified form element.

_IEFormElementRadioSelect Set the value of a specified form element.

_IEFormElementSetValue Set the value of a specified Form Element.

_IEFormGetCollection Returns a collection object variable representing the Forms in the document.

_IEFormGetObjByName Returns an object reference to a Form by name.

_IEFormImageClick Simulate a mouse click on an <input type=image>. Match by sub-string match of alt text, name or src.

_IEFormReset Reset a specified Form.

_IEFormSubmit Submit a specified Form.

_IEFrameGetCollection Returns a collection object containing the frames in a FrameSet or the iFrames on a normal page.

_IEFrameGetObjByName Returns an object reference to a Frame by name.

_IEGetObjByName Returns an object variable by name or id.

_IEHeadInsertEventScript Inserts a Javascript into the Head of the document.

_IEImgClick Simulate a mouse click on an image. Match by sub-string match of alt text, name, or src.

_IEImgGetCollection Returns a collection object variable representing the IMG tags in the document.

_IEIsFrameSet Checks to see if the specified Window contains a FrameSet.

_IELinkClickByIndex Simulate a mouse click on a link by 0-based index (in source order).

_IELinkClickByText Simulate a mouse click on a link with text sub-string matching the string provided.

_IELinkGetCollection Returns a collection object containing all links in the document.

_IELoadWait Wait for a browser page load to complete before returning.

_IELoadWaitTimeout Retrieve or set the current value in milliseconds _IELoadWait will try before timing out.

_IENavigate Directs an existing browser window to navigate to the specified URL.

_IEPropertyGet Returns a select property of the Browser.

_IEPropertySet Set a select property of the Browser.

_IEQuit Close the browser and remove the object reference to it.

_IETableGetCollection Returns a collection object variable representing all the tables in a document.

_IETableWriteToArray Reads the contents of a Table into an array.

_IETagNameAllGetCollection Returns a collection object all elements in the document or document hierarchy in source order.

_IETagNameGetCollection Returns a collection object of all elements in the object with the specified TagName.

#)

Link to comment
Share on other sites

I have not understood your question...

the link of a page with the vbs script and the explanation is in my previous post:

http://www.motobit.com/tips/detpg_uploadvbaie/

and the question is:

how to simulate a form submit passing via POST method a file encoded in multpart mode...

my point of view can be an extention of inetget function... not only GETbut also POST...

my problem now is:

- I need to collect some files (every time the same file) and send to a web page ... (statistics: text and graph)

- in the page I have a field like this: <input type=file name=fname>

I hope to have explained my problem better (with my poor english!)

Link to comment
Share on other sites

Hi,

not really. :) Could you explain it step-by-step in prosa what you want to do. And how would you do it manually?

So long,

Mega

Scripts & functions Organize Includes Let Scite organize the include files

Yahtzee The game "Yahtzee" (Kniffel, DiceLion)

LoginWrapper Secure scripts by adding a query (authentication)

_RunOnlyOnThis UDF Make sure that a script can only be executed on ... (Windows / HD / ...)

Internet-Café Server/Client Application Open CD, Start Browser, Lock remote client, etc.

MultipleFuncsWithOneHotkey Start different funcs by hitting one hotkey different times

Link to comment
Share on other sites

Is that German for prostitue :) ? :P

HI,

:D no. It is short from latin : prosa oratio.

I dunno the correct English word for ... when you desribe with your own words program code.

prose???

So long,

Mega

PS: You meant this: http://dict.leo.org/ende?lp=ende&p=/oH...h=prostituierte

moll die Prostituierte

prostitute die Prostituierte

working girl [obs.] [sl.] die Prostituierte

Edit: Yeah I got it http://en.wikipedia.org/wiki/Prose

Edited by th.meger

Scripts & functions Organize Includes Let Scite organize the include files

Yahtzee The game "Yahtzee" (Kniffel, DiceLion)

LoginWrapper Secure scripts by adding a query (authentication)

_RunOnlyOnThis UDF Make sure that a script can only be executed on ... (Windows / HD / ...)

Internet-Café Server/Client Application Open CD, Start Browser, Lock remote client, etc.

MultipleFuncsWithOneHotkey Start different funcs by hitting one hotkey different times

Link to comment
Share on other sites

ok, I try...

suppose to have a form like this

<Form Action=http://127.0.0.30/util/up/free/upload.asp
  Method=Post ENCTYPE="multipart/form-data">
  <Input Type=File Name=FileField>
  <Input Type=Submit>
 </Form>

and in the web server (Apache/php) this code

<HTML>
<BODY>

<?

$uploaddir = '../files/';

print_r($_FILES);

$uploadfile = $uploaddir . $_FILES['FileField']['name'];
if (move_uploaded_file($_FILES['FileField']['tmp_name'], $uploadfile)) {
   echo "OK ($uploadfile)";
} else {
   echo "KO failed to upload! ($uploadfile)\n";
} 
?>
</BODY>
</HTML>

now, you can open browser, go to the form url, choose the file and finally press submit for upload it...

my goal is to do all in automatic mode, with a scheduled task...

I have now the vbs script (see attach and the webpage http://www.motobit.com/tips/detpg_uploadvbaie/ for explanation)

this script can be called in this way:

cscript|wscript fupload.vbs file url fieldname
file ... Local file to upload
url ... URL which can accept uploaded data
fieldname ... Name of the source form field.

... the script send the data exactly like the form submit.

again...

if will be possible to implement this in autoit?

I need to do some check before send data and AutoIt is for me the best way...

my idea now is to call from Autoit the vbs scrpt but....

- vbs run in a separate shell (new explorer istance)

- how intercept and manage error inside vbs? my autoit procedure must know if the upload is OK or not...

tks to all (for all)

fupload.zip

Link to comment
Share on other sites

For those too lazy to dl the script, here is the source:

'Upload file using http protocol And multipart/form-data
'v1.01
'2001 Antonin Foller, PSTRUH Software
do_vbsUpload

Sub do_vbsUpload()
  'We need at least two arguments (File + URL)
  If WScript.Arguments.Count < 2 Then InfoEcho
  
  'Are some required objects missing?
  If InStr(CheckRequirements, "Error") > 0 Then InfoEcho
  
  Dim FileName, DestURL, FieldName
  FieldName = "uploadfile" 'Default field name

  Dim aCounter, Arg
  aCounter = 1 'Argument counter
  For Each Arg In WScript.Arguments
    Select Case aCounter
      Case 1: FileName = Arg
      Case 2: DestURL = Arg
      Case 3: FieldName = Arg
    End Select
    aCounter = aCounter + 1
  Next
  
  UploadFile DestURL, FileName, FieldName
End Sub



'******************* upload - begin
'Upload file using input type=file
Sub UploadFile(DestURL, FileName, FieldName)
  'Boundary of fields.
  'Be sure this string is NOT in the source file
  Const Boundary = "-2"
  
  Dim FileContents, FormData
  'Get source file as a binary data.
  FileContents = GetFile(FileName)
  
  'Build multipart/form-data document
  FormData = BuildFormData(FileContents, Boundary, FileName, FieldName)
  
  'Post the data to the destination URL
  IEPostBinaryRequest DestURL, FormData, Boundary
End Sub

'Build multipart/form-data document with file contents and header info
Function BuildFormData(FileContents, Boundary, FileName, FieldName)
  Dim FormData, Pre, Po
  Const ContentType = "application/upload"
  
  'The two parts around file contents in the multipart-form data.
  Pre = "--" + Boundary + vbCrLf + mpFields(FieldName, FileName, ContentType)
  Po = vbCrLf + "--" + Boundary + "--" + vbCrLf
  
  'Build form data using recordset binary field
  Const adLongVarBinary = 205
  Dim RS: Set RS = CreateObject("ADODB.Recordset")
  RS.Fields.Append "b", adLongVarBinary, Len(Pre) + LenB(FileContents) + Len(Po)
  RS.Open
  RS.AddNew
    Dim LenData
    'Convert Pre string value to a binary data
    LenData = Len(Pre)
    RS("b").AppendChunk (StringToMB(Pre) & ChrB(0))
    Pre = RS("b").GetChunk(LenData)
    RS("b") = ""
    
    'Convert Po string value to a binary data
    LenData = Len(Po)
    RS("b").AppendChunk (StringToMB(Po) & ChrB(0))
    Po = RS("b").GetChunk(LenData)
    RS("b") = ""
    
    'Join Pre + FileContents + Po binary data
    RS("b").AppendChunk (Pre)
    RS("b").AppendChunk (FileContents)
    RS("b").AppendChunk (Po)
  RS.Update
  FormData = RS("b")
  RS.Close
  BuildFormData = FormData
End Function

'sends multipart/form-data to the URL using IE
Function IEPostBinaryRequest(URL, FormData, Boundary)
  'Create InternetExplorer
  Dim IE: Set IE = CreateObject("InternetExplorer.Application")
  
  'You can uncoment next line to see form results
  IE.Visible = True
   
  'Send the form data to URL as POST multipart/form-data request
  IE.Navigate URL, , , FormData, _
    "Content-Type: multipart/form-data; boundary=" + Boundary + vbCrLf

  Do While IE.Busy
    Wait 1, "Upload to " & URL
  Loop
  
  'Get a result of the script which has received upload
  On Error Resume Next
  IEPostBinaryRequest = IE.document.body.innerHTML
'  IE.Quit
End Function

'Infrormations in form field header.
Function mpFields(FieldName, FileName, ContentType)
  Dim MPTemplate 'template for multipart header
  MPTemplate = "Content-Disposition: form-data; name=""{field}"";" + _
   " filename=""{file}""" + vbCrLf + _
   "Content-Type: {ct}" + vbCrLf + vbCrLf
  Dim Out
  Out = Replace(MPTemplate, "{field}", FieldName)
  Out = Replace(Out, "{file}", FileName)
  mpFields = Replace(Out, "{ct}", ContentType)
End Function


Sub Wait(Seconds, Message)
  On Error Resume Next
  CreateObject("wscript.shell").Popup Message, Seconds, "", 7
End Sub


'Returns file contents as a binary data
Function GetFile(FileName)
  Dim Stream: Set Stream = CreateObject("ADODB.Stream")
  Stream.Type = 1 'Binary
  Stream.Open
  Stream.LoadFromFile FileName
  GetFile = Stream.Read
  Stream.Close
End Function

'Converts OLE string to multibyte string
Function StringToMB(S)
  Dim I, B
  For I = 1 To Len(S)
    B = B & ChrB(Asc(Mid(S, I, 1)))
  Next
  StringToMB = B
End Function
'******************* upload - end

'******************* Support
'Basic script info
Sub InfoEcho()
  Dim Msg
  Msg = Msg + "Upload file using http and multipart/form-data" & vbCrLf
  Msg = Msg + "Copyright (C) 2001 Antonin Foller, PSTRUH Software" & vbCrLf
  Msg = Msg + "use" & vbCrLf
  Msg = Msg + "[cscript|wscript] fupload.vbs file url [fieldname]" & vbCrLf
  Msg = Msg + "  file ... Local file to upload" & vbCrLf
  Msg = Msg + "  url ... URL which can accept uploaded data" & vbCrLf
  Msg = Msg + "  fieldname ... Name of the source form field." & vbCrLf
  Msg = Msg + vbCrLf + CheckRequirements
  WScript.Echo Msg
  WScript.Quit
End Sub

'Checks if all of required objects are installed
Function CheckRequirements()
  Dim Msg
  Msg = "This script requires some objects installed to run properly." & vbCrLf
  Msg = Msg & CheckOneObject("ADODB.Recordset")
  Msg = Msg & CheckOneObject("ADODB.Stream")
  Msg = Msg & CheckOneObject("InternetExplorer.Application")
  CheckRequirements = Msg
'  MsgBox Msg
End Function

'Checks if the one object is installed.
Function CheckOneObject(oClass)
  Dim Msg
  On Error Resume Next
  CreateObject oClass
  If Err = 0 Then Msg = "OK" Else Msg = "Error:" & Err.Description
  CheckOneObject = oClass & " - " & Msg & vbCrLf
End Function
'******************* Support - end

Looking at this, it is possible to do this using the TCP functions of AutoIt and directly sending the data.

Does anyone else know the HTTP protocol for the application-type "application/upload" ?

#)

Edited by nfwu
Link to comment
Share on other sites

I managed to figure that FormData is equal to this:

---2<CRLF>
Content-Disposition: form-data; name="THENAMEOFTHEFIELD"; filename="NAMEOFTHEFILE"<CRLF>
Content-Type: application/upload<CRLF>
<CRLF>
FILE_CONTENTS_IN_BINARY_GOES_HERE_AS_DESCRIBED_BY_FUNCTION_BUILDFORMDATA<CRLF>
---2--<CRLF>

All that is needed now is to pass the value for FormData, Boundary = "-2" (The string "-2"), and the URL to an AutoIt version of

IEPostBinaryRequest.

#)

Link to comment
Share on other sites

from MSDN documentation:

http://msdn.microsoft.com/workshop/browser/webbrowser/reference/methods/navigate.asp

and

http://msdn.microsoft.com/workshop/browser/webbrowser/reference/ifaces/iwebbrowser2/navigate.asp

IE.Navigate( _

url As String, _

[Flags As Variant,]_

[TargetFrameName As Variant,] _

[PostData As Variant,] _

[Headers As Variant])

where

Parameters

url

Required. A String expression that evaluates to the URL, full path, or Universal Naming Convention (UNC) location and name of the resource to display.

Flags

Optional. A constant or value that specifies whether to add the resource to the history list, whether to read from or write to the cache, and whether to display the resource in a new window. The variable can be a combination of the values defined by the BrowserNavConstants enumeration.

TargetFrameName

Optional. String expression that evaluates to the name of an HTML frame in URL to display in the browser window. The possible values for this parameter are:

_BLANK

Load the link into a new unnamed window.

_PARENT

Load the link into the immediate parent of the document the link is in.

_SELF

Load the link into the same window the link was clicked in.

_TOP

Load the link into the full body of the current window.

<WINDOW_NAME>

A named HTML frame. If no frame or window exists that matches the specified target name, a new window is opened for the specified link.

PostData

Optional. Data to send to the server during the HTTP POST transaction. For example, the POST transaction is used to send data gathered by an HTML form to a program or script. If this parameter does not specify any post data, the Navigate method issues an HTTP GET transaction. This parameter is ignored if URL is not an HTTPURL.

Headers

Optional. A value that specifies additional HTTP headers to send to the server. These headers are added to the default Microsoft Internet Explorer headers. The headers can specify things like the action required of the server, the type of data being passed to the server, or a status code. This parameter is ignored if URL is not an HTTPURL.

and about POSTDATA format:

The post data specified by PostData is passed as a SAFEARRAY Data Type structure. The VARIANT should be of type VT_ARRAY and point to a SAFEARRAY Data Type. The SAFEARRAY Data Type should be of element type VT_UI1, dimension one, and have an element count equal to the number of bytes of post data.

and is possible to read more about Safearray detail in the Microsoft site

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/automat/html/9ec8025b-4763-4526-ab45-390c5d8b3b1e.asp

The definition for a safearray varies, depending on the target operating system platform. On 32-bit Windows systems, both the cbElements and cLocks parameters are unsigned long integers, and the handle parameter is omitted. On 16-bit Windows systems, cbElements and cLocks are unsigned short integers The handle parameter is retained for compatibility with earlier software. For example:
C++

typedef struct FARSTRUCT tagSAFEARRAY {

   unsigned short cDims;       // Count of dimensions in this array.

   unsigned short fFeatures;   // Flags used by the SafeArray

                        // routines documented below.

#if defined(WIN32)

   unsigned long cbElements;   // Size of an element of the array.

                        // Does not include size of

                        // pointed-to data.

   unsigned long cLocks;      // Number of times the array has been 

                        // locked without corresponding unlock.

#else

   unsigned short cbElements;

   unsigned short cLocks;

   unsigned long handle;      // Used on Macintosh only.

#endif

   void HUGEP* pvData;           // Pointer to the data.

   SAFEARRAYBOUND rgsabound[1];   // One bound for each dimension.

} SAFEARRAY;

mmmm...

can this information be usefull?

Link to comment
Share on other sites

  • 2 weeks later...

If you can't get it to work you might find Curl the answer- a command line tool, also comes as a dll

Curl

This from their doc file:

UPLOADING

FTP

Upload all data on stdin to a specified ftp site:

curl -T - ftp://ftp.upload.com/myfile

Upload data from a specified file, login with user and password:

curl -T uploadfile -u user:passwd ftp://ftp.upload.com/myfile

Upload a local file to the remote site, and use the local file name remote

too:

curl -T uploadfile -u user:passwd ftp://ftp.upload.com/

Upload a local file to get appended to the remote file using ftp:

curl -T localfile -a ftp://ftp.upload.com/remotefile

Curl also supports ftp upload through a proxy, but only if the proxy is

configured to allow that kind of tunneling. If it does, you can run curl in

a fashion similar to:

curl --proxytunnel -x proxy:port -T localfile ftp.upload.com

HTTP

Upload all data on stdin to a specified http site:

curl -T - http://www.upload.com/myfile

Note that the http server must have been configured to accept PUT before

this can be done successfully.

For other ways to do http data upload, see the POST section below.

==============

Regards Freizag :)

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...