Posting multipart data...

Everything else that doesn't fall into one of the other PB categories.
User avatar
DoubleDutch
Addict
Addict
Posts: 3220
Joined: Thu Aug 07, 2003 7:01 pm
Location: United Kingdom
Contact:

Posting multipart data...

Post by DoubleDutch »

Anyone come up with a routine to post multipart data to a website?

Here is an example in Java that should translate to PureBasic if anyone wants to have a go...

Code: Select all

Uploading images or other files to a web server is easy using Java ME. In this example a HttpConnection is used and the file will be posted to the server. What we do is pretty much the same as using an HTML form to upload a file.

Download MIDlet and source code here>>

Here is an HTML example.

<form action="http://myserver/post.php" enctype ="multipart/form-data" method="post">
<input type="file" name="uploadedfile">
<input type="submit">
</form>

Here is the php file receiving the posted file.

//post.php
<?php

$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
    " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
}

?>

When doing the same posting in Java ME there is a little more that must be done.

First we must set the request method to POST and to set the correct content-type in the header. This should be done before any InputStream or OutputStream are opened for the connection.

The message is split into three sections:
1. Message1 including the boundary start, content-disposition and what type of file we are sending.
2. The byte array of the file.
3. Message2 including the boundary end.

In this example the file is sent in chunks of 1024 bytes.

private final String CrLf = "\r\n";

    
private void httpConn(){
    HttpConnection conn = null;
    OutputStream os = null;
    InputStream is = null;
    
    String url = "";
    url = "http://myserver/post.php";

    try{
        System.out.println("url:" + url);
        conn = (HttpConnection)Connector.open(url);
        conn.setRequestMethod(HttpConnection.POST);

        String postData = "";

        InputStream imgIs = getClass().getResourceAsStream("/image.jpg");
        byte []imgData = new byte[imgIs.available()];
        imgIs.read(imgData);

        String message1 = "";
        message1 += "-----------------------------4664151417711" + CrLf;
        message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"image.jpg\"" + CrLf;
        message1 += "Content-Type: image/jpeg" + CrLf;
        message1 += CrLf;

        // the image is sent between the messages in the multipart message.

        String message2 = "";
        message2 += CrLf + "-----------------------------4664151417711--" + CrLf;               

        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------4664151417711");
        // might not need to specify the content-length when sending chunked data.
        // conn.setRequestProperty("Content-Length", String.valueOf((message1.length() + message2.length() + imgData.length)));

        System.out.println("open os");
        os = conn.openOutputStream();

        System.out.println(message1);
        os.write(message1.getBytes());

        // SEND THE IMAGE
        int index = 0;
        int size = 1024;
        do{
            System.out.println("write:" + index);
            if((index+size)>imgData.length){
                size = imgData.length - index; 
            }
            os.write(imgData, index, size);
            index+=size;
        }while(index<imgData.length);
        System.out.println("written:" + index);            

        System.out.println(message2);
        os.write(message2.getBytes());
        os.flush();

        System.out.println("open is");
        is = conn.openInputStream();

        char buff = 512;
        int len;
        byte []data = new byte[buff];
        do{
            System.out.println("READ");
            len = is.read(data);

            if(len > 0){
                System.out.println(new String(data, 0, len));
            }
        }while(len>0);

        System.out.println("DONE");
        
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        System.out.println("Close connection");
        try{
            os.close();
        }catch(Exception e){}
        try{
            is.close();
        }catch(Exception e){}
        try{
            conn.close();            
        }catch(Exception e){}
    }
}
 
https://deluxepixel.com <- My Business website
https://reportcomplete.com <- School end of term reports system
User avatar
Joakim Christiansen
Addict
Addict
Posts: 2452
Joined: Wed Dec 22, 2004 4:12 pm
Location: Norway
Contact:

Re: Posting multipart data...

Post by Joakim Christiansen »

I did that once:
http://www.purebasic.fr/english/viewtop ... 12&t=34916
Look at my HttpPostMultipart() procedure for ideas. But please note that it is not meant to be a finished solution to be used by anyone... it was just something quickly hacked together.

Actually I have gotten quite some experience making web bots now (hence the mask in my picture), so if there is other tricky stuff (like session cookies and whatnot) which makes it hard for you to make this uploader thingy of yours then you know where to find me. A good thing is also to analyze what your browser does by using Wireshark, no excuse, get it now!

With Wireshark set capture filter to "tcp port http" and then switch between
http.request.method == "POST"
and
http.request.method == "GET"
as display filters to see what your browser sends.
I like logic, hence I dislike humans but love computers.
Post Reply