×

Discussion Board

Results 1 to 13 of 13

Thread: HTTP Post Image

Hybrid View

  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    9

    HTTP Post Image

    Hi! I am trying the sample code found here. The HttpMultipartRequest class is the same, while the MIDlet being used for testing is as follows:
    Code:
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.io.*;
    import java.io.*;
    import java.util.Hashtable;
    import javax.microedition.io.file.FileConnection;
    
    public class PostFile extends MIDlet implements Runnable, CommandListener{
               
        private Form form = null;
        private Gauge gauge = null;
        private Command exitCommand;
        private Command uploadCommand;
        
        public PostFile(){
            form = new Form("Upload File");
            gauge = new Gauge("Progress:", true, 100, 0);
            form.append(gauge);
            
            exitCommand = new Command("Exit", Command.EXIT, 0);
            uploadCommand = new Command("Upload", Command.SCREEN, 0);
            form.addCommand(exitCommand);
            form.addCommand(uploadCommand);
            
            form.setCommandListener(this);
        }
        
        public void startApp() {
            Display.getDisplay(this).setCurrent(form);
        }
        
        public void pauseApp() {
        }
        
        public void destroyApp(boolean unconditional) {
        }
        
        private void progress(int total, int current){
            int percent = (int) (100 * ((float)current/(float)total));
            gauge.setValue(percent);
        }
        
        public void run() {
            try {
                send();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }    
        
        private void send() throws Exception {
            
            byte[] fileBytes = getByteArray(Image.createImage("/image.png")); //retrieve file bytes with your own code
    			
            Hashtable params = new Hashtable();
            params.put("custom_param", "param_value");
            params.put("custom_param2", "param_value2");
    
            HttpMultipartRequest req = new HttpMultipartRequest(
                    "http://localhost:80/uploadScript.php",
                    params,
                    "upload_field", "image.png", "image/png", fileBytes
            );
    
            byte[] response = req.send();
        }
         
        
        public void commandAction(javax.microedition.lcdui.Command command, javax.microedition.lcdui.Displayable displayable) {
            if(command == exitCommand){
                this.notifyDestroyed();
            }else if(command == uploadCommand){
                new Thread(this).start();
            }
        }
        
        public byte[] getByteArray(Image image) {
            int raw[] = new int[image.getWidth() * image.getHeight()];
            image.getRGB(raw, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
            byte rawByte[] = new byte[image.getWidth() * image.getHeight() * 4];
            int n = 0;
            for (int i = 0; i < raw.length; i++) {
                int ARGB = raw[i];
                int a = (ARGB & 0xff000000) >> 24;
                int r = (ARGB & 0xff0000) >> 16;
                int g = (ARGB & 0xff00) >> 8;
                int b = ARGB & 0xff;
                rawByte[n] = (byte) b;
                rawByte[n + 1] = (byte) g;
                rawByte[n + 2] = (byte) r;
                rawByte[n + 3] = (byte) a;
                n += 4;
            }
            System.out.println("raw(int) length is: " + raw.length);
            System.out.println("raw(Byte) length is: " + rawByte.length);
            raw = null;
            return rawByte;
        }
    }
    The PHP file is as follows:
    Code:
    <?php
     
    $filesize = filesize($_FILES['upload_field']['tmp_name']);
     
    echo "The uploaded file size is " . $filesize . " bytes\n";
     
    foreach($_POST as $key => $value)
    {
    	echo "Parameter name: " . $key . ", value: " . $value . "\n";
    }
     
    ?>
    When I try to run it, I get the following:
    Code:
    raw(int) length is: 65536
    raw(Byte) length is: 262144
    java.io.IOException: error 0 during TCP write 
            at com.sun.midp.io.j2me.socket.Protocol.writeBytes(Protocol.java:360)
            at com.sun.midp.io.BaseOutputStream.write(ConnectionBaseAdapter.java:830)
            at java.io.DataOutputStream.write(DataOutputStream.java:90)
            at com.sun.midp.io.j2me.http.Protocol.sendRequestBody(Protocol.java:1896)
            at com.sun.midp.io.j2me.http.Protocol.sendRequest(Protocol.java:1562)
            at com.sun.midp.io.j2me.http.Protocol.writeBytes(Protocol.java:1032)
            at com.sun.midp.io.BaseOutputStream.write(ConnectionBaseAdapter.java:830)
            at java.io.OutputStream.write(OutputStream.java:58)
            at HttpMultipartRequest.send(HttpMultipartRequest.java:109)
            at PostFile.send(PostFile.java:91)
            at PostFile.run(PostFile.java:71)
    The file I am using can be downloaded here.

    Hope you can help me.
    Thanks.

  2. #2
    Super Contributor
    Join Date
    Mar 2008
    Location
    The Capital of INDIA
    Posts
    4,328

    Re: HTTP Post Image

    Thanks with Regards,

    R a j - The K e r n e l


    Join Delhi-NCR Nokia Developer's Community,

  3. #3
    Registered User
    Join Date
    Feb 2009
    Posts
    9

    Re: HTTP Post Image

    I have checked these, but to no avail. And I am using PHP for the server part, not Tomcat/ Servlet. Well, has anyone been able to use the code given in the Wiki? :S Can you try using the code I've provided?

  4. #4
    Super Contributor
    Join Date
    Mar 2008
    Location
    The Capital of INDIA
    Posts
    4,328

    Re: HTTP Post Image

    Hi,
    I guess no body will be having the time that he can do the code for you and then test the issues...

    What exactly you are doing ..you are calling the class found here,with your midlet...
    http://wiki.forum.nokia.com/index.ph...load_with_J2ME



    Please try to debug the code and check that what can be the reason for the same.Try to print the values you are passing to the HTTP class....are these values null or not...
    Thanks with Regards,

    R a j - The K e r n e l


    Join Delhi-NCR Nokia Developer's Community,

  5. #5
    Registered User
    Join Date
    Feb 2009
    Posts
    9

    Re: HTTP Post Image

    I've been able to make a version I got from SE's site work successfully.
    Code:
        ...
        private final String FILE = "/image.png";
        private final String URL = "http://localhost:80/post.php";
        
        private final String CrLf = "\r\n";
    
        private void httpConn(){
            HttpConnection conn = null;
            OutputStream os = null;
            InputStream is = null;
            
            try{
                System.out.println("url:" + URL);
                conn = (HttpConnection)Connector.open(URL);
                conn.setRequestMethod(HttpConnection.POST);
    
                String postData = "";
    
                InputStream imgIs = getClass().getResourceAsStream(FILE);
                byte []imgData = new byte[imgIs.available()];
                imgIs.read(imgData);
    
                String message1 = "";
                message1 += "-----------------------------4664151417711" + CrLf;
                message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"" + FILE + "\"" + CrLf;
                message1 += "Content-Type: image/png" + CrLf;
                message1 += CrLf;
    
                // the image is sent between the messages ni 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;
                    progress(imgData.length, index); // update the progress bar.
    
                }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){}
            }
        }    
        ...

    With the post.php file as follows:
    Code:
    <?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, try again!";
    }
    ?>
    But how do I send data along with the file?

    For example I want to send a string, Description, which contains a little description and at the server side, I want to retrieve it using $_POST before doing some processing on it. By using simple HTTP Post, it would have been like that:
    Code:
                ...
                try {
                            
                http = (HttpConnection)Connector.open(url);
                http.setRequestProperty("User-Agent","Profile/MIDP-  1.0 Configuration/CLDC-1.0");
                http.setRequestProperty("Content-Language", "en-CA");
                http.setRequestProperty("CONTENT-TYPE", "application/x-www-form-urlencoded");
                http.setRequestProperty( "Connection", "close" );
    
                http.setRequestMethod(http.POST);
    
                String req = "txt="+part+"\r\n" ;                
    
                http.setRequestProperty("Content-Length", Integer.toString( req.length()));
    
                out = http.openOutputStream();
    
                int rlength = req.length();
                for ( int i = 0; i < rlength; i++ )
                        out.write( req.charAt(i));
    
                in = http.openInputStream();
    
                rc = http.getResponseCode();
    
                int ch;
                StringBuffer buff = new StringBuffer();
                while ( (ch = in.read())!= -1){
                    buff.append( (char) ch);
                }
    
                form.append(new StringItem("Response: ", buff.toString()));
                ...
    In the above, part is the value of 'txt' and at the server-side, we retrieve it by uisng $_POST['txt'].

    So, how do I send data as well as a file? This has been implemented in the coding I gave in the first post, but I don't know how to implement it in the current case.

  6. #6
    Regular Contributor
    Join Date
    Mar 2008
    Posts
    198

    Re: HTTP Post Image

    Quote Originally Posted by girish3110 View Post
    So, how do I send data as well as a file? This has been implemented in the coding I gave in the first post, but I don't know how to implement it in the current case.
    I'm not sure what you are asking... Are you asking how to send more than one data item at a time? If so, that depends entirely on the whatever is receiving the data is willing to understand.

    The PHP $_POST variable is very limited in this respect. It is expecting to receive items in the following way:

    Code:
    name1=value1&name2=value2&name3=value3
    If one of your values contains any of the special symbols (e.g. &, =, space, etc) then it will be encoded using HTTP... e.g. space will be encoded as %20

    It is your responsibility to encode the data you send from the phone correctly (if you're using HTML, the browser does this for you, but you're not using HTML or a browser so you have to do it yourself).

    A MUCH better solution is to send (and receive) XML. But even then, if you're sending binary data you will still need to encode it in some way (e.g. base64). You'll have to change your PHP scripts of course to use XML instead of $_POST.

    - Mike
    NAVTEQ Network for Developers
    The community for developing innovative location-based applications
    http://NN4D.com

  7. #7
    Registered User
    Join Date
    Feb 2009
    Posts
    9

    Re: HTTP Post Image

    Yes, I want to send several data...in addition to the picture...

    What I want to do is used here:
    http://wiki.forum.nokia.com/index.ph...load_with_J2ME

    In the above, it is possible to add other parameters... But I don't know how to set it in my code..

  8. #8
    Regular Contributor
    Join Date
    Mar 2008
    Posts
    198

    Re: HTTP Post Image

    Quote Originally Posted by girish3110 View Post
    What I want to do is used here:
    http://wiki.forum.nokia.com/index.ph...load_with_J2ME
    In the above, it is possible to add other parameters... But I don't know how to set it in my code..
    So now I'm really confused... if you already have the code, and it does what you want, why can't you make it work? What error messages are you getting? Are you sure you are using the code correctly? If you are sure, how do you know?

    I'm not sure that this code really does do what you want, since it will only work with text based data... HTTP Multipart does not handle binary data (like bytes equal to 0 for example) if you're trying to send binary data (like a picture) it surely won't work, except accidentally.

    You'll note that the example you point to neatly skips the bit about how you load and encode the data from the picture file - getFileBytes(). Generally, you'd use base64 (at both client and server end of course).

    - Mike
    NAVTEQ Network for Developers
    The community for developing innovative location-based applications
    http://NN4D.com

  9. #9
    Registered User
    Join Date
    Feb 2009
    Posts
    9

    Thumbs up Re: HTTP Post Image

    I've made it work... The picture and text data is sent together... Here is the edited part:
    Code:
                String message1 = "";
                message1 += "-----------------------------4664151417711" + CrLf;
                message1 += "Content-Disposition: form-data; name=\"username\"" + CrLf;
                message1 += CrLf + "Girish" + CrLf;
                message1 += "-----------------------------4664151417711" + CrLf;
                message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.png\"" + CrLf;
                message1 += "Content-Type: image/png" + CrLf;
                message1 += CrLf;
    Together with the picture, which is saved as test.png, the data 'username' is also sent. You can then retrieve the data for the latter with $_POST['username'] .

  10. #10
    Registered User
    Join Date
    Apr 2013
    Posts
    1

    Re: HTTP Post Image

    girish what SE site you are talking about could you please give me d link of it..?

  11. #11
    Super Contributor
    Join Date
    Jun 2003
    Location
    Cheshire, UK
    Posts
    7,395

    Re: HTTP Post Image

    Girish3110 was last here four years ago. Please start a new thread and post your question, I'm sure someone will help you.

    Graham.

  12. #12
    Nokia Developer Champion
    Join Date
    Mar 2003
    Posts
    4,104

    Re: HTTP Post Image

    Sony Ericsson Developer World
    That page, nowadays Sony Mobile, closed most of its J2ME efforts.

    If you search for “4664151417711” and “Ericsson” on the Internet, you get several hits showing the source in total.

Similar Threads

  1. HTTP symbian example - post not working
    By tomasz.florczak in forum Symbian C++
    Replies: 4
    Last Post: 2011-06-21, 06:09
  2. HTTP POST is not giving EGotResponseBodyData event
    By parthasaradhi6 in forum Symbian C++
    Replies: 4
    Last Post: 2009-11-23, 15:05
  3. Uploading a file using http post problem
    By mynick1000 in forum Symbian Networking & Messaging (Closed)
    Replies: 16
    Last Post: 2009-08-01, 14:28
  4. sending HTTP POST - error 36
    By tomasz.florczak in forum Symbian C++
    Replies: 4
    Last Post: 2008-03-21, 20:22
  5. how to cut some part of Image
    By mshouab in forum Mobile Java Media (Graphics & Sounds)
    Replies: 2
    Last Post: 2006-08-04, 09:05

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •