gladiatorohit 0 Newbie Poster

Hello everybody,

I am trying to send an image from midlet to servlet. I have converted the image into its BASE64 format. I have to send it now to a servlet.

Please help me how to read the sent bytes in servlet..??
And where and how will be the received bytes will be stored in tomcat...??

I have pasted the code i have tried...please help me out...

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hello;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import org.bouncycastle.util.encoders.Base64;


/**
 * @author Administrator
 */
public class HelloMIDlet extends MIDlet implements CommandListener {

    private boolean midletPaused = false;

    //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">                      
    private Command exitCommand;
    private Command okCommand1;
    private Command exitCommand1;
    private Command screenCommand;
    private Command okCommand;
    private Command Next;
    private Command Send;
    private Command Exit;
    private Command okCommand2;
    private Command cancelCommand;
    private Form form;
    private StringItem stringItem;
    private Form form1;
    private TextField textField;
    private ImageItem imageItem;
    private Form form2;
    private Image image1;
    private Ticker ticker;
    //</editor-fold>                    

    /**
     * The HelloMIDlet constructor.
     */
    public HelloMIDlet() {
    }

    //<editor-fold defaultstate="collapsed" desc=" Generated Methods ">                       
    //</editor-fold>                     

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">                                           
    /**
     * Initilizes the application.
     * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
     */
    private void initialize() {                                         
        // write pre-initialize user code here
                                           
        // write post-initialize user code here
    }                            
    //</editor-fold>                          

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">                                        
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {                                      
        // write pre-action user code here
        switchDisplayable(null, getForm());                                        
        // write post-action user code here
    }                             
    //</editor-fold>                           

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">                                         
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {                                       
        // write pre-action user code here
                                         
        // write post-action user code here
    }                              
    //</editor-fold>                            

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">                                              
    /**
     * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
     * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {                                            
        // write pre-switch user code here
        Display display = getDisplay();                                               
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }                                             
        // write post-switch user code here
    }                                   
    //</editor-fold>                                 

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">                                                 
    /**
     * Called by a system to indicated that a command has been invoked on a particular displayable.
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {                                               
        // write pre-action user code here
        if (displayable == form) {                                           
            if (command == exitCommand) {                                         
                // write pre-action user code here
                exitMIDlet();                                           
                // write post-action user code here
            } else if (command == okCommand) {                                          
                // write pre-action user code here
                switchDisplayable(null, getForm1());                                           
                // write post-action user code here
            }                                           
        } else if (displayable == form1) {
            if (command == Next) {                                         
                // write pre-action user code here
                switchDisplayable(null, getForm2());                                           
                // write post-action user code here
            } else if (command == exitCommand1) {                                          
                // write pre-action user code here
                exitMIDlet();                                           
                // write post-action user code here
            }                                           
        } else if (displayable == form2) {
            if (command == Exit) {                                         
                // write pre-action user code here
                exitMIDlet();                                            
                // write post-action user code here
            } else if (command == Send) {                                           
                // write pre-action user code here
                                            
                // write post-action user code here
            }                                                   
        }                                                 
        // write post-action user code here
    }                                
    //</editor-fold>                              





    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">                                   
    /**
     * Returns an initiliazed instance of exitCommand component.
     * @return the initialized component instance
     */
    public Command getExitCommand() {
        if (exitCommand == null) {                                 
            // write pre-init user code here
            exitCommand = new Command("Exit", Command.EXIT, 0);                                   
            // write post-init user code here
        }                         
        return exitCommand;
    }
    //</editor-fold>                       

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: form ">                                   
    /**
     * Returns an initiliazed instance of form component.
     * @return the initialized component instance
     */
    public Form getForm() {
        if (form == null) {                                 
            // write pre-init user code here
            form = new Form("Welcome", new Item[] { getStringItem() });                                    
            form.addCommand(getExitCommand());
            form.addCommand(getOkCommand());
            form.setCommandListener(this);                                  
            // write post-init user code here
        }                         
        return form;
    }
    //</editor-fold>                       

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: stringItem ">                                   
    /**
     * Returns an initiliazed instance of stringItem component.
     * @return the initialized component instance
     */
    public StringItem getStringItem() {
        if (stringItem == null) {                                 
            // write pre-init user code here
            stringItem = new StringItem("Hello user...", "Press show to see image");                                   
            // write post-init user code here
        }                         
        return stringItem;
    }
    //</editor-fold>                       





    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: form1 ">                                   
    /**
     * Returns an initiliazed instance of form1 component.
     * @return the initialized component instance
     */
    public Form getForm1() {
        if (form1 == null) {                                 
            // write pre-init user code here
            form1 = new Form("form1", new Item[] { getTextField(), getImageItem() });                                    
            form1.addCommand(getExitCommand1());
            form1.addCommand(getNext());
            form1.setCommandListener(this);                                  
            // write post-init user code here
        }                         
        return form1;
    }
    //</editor-fold>                       



    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: okCommand1 ">                                   
    /**
     * Returns an initiliazed instance of okCommand1 component.
     * @return the initialized component instance
     */
    public Command getOkCommand1() {
        if (okCommand1 == null) {                                 
            // write pre-init user code here
            okCommand1 = new Command("Ok", Command.OK, 0);                                   
            // write post-init user code here
        }                         
        return okCommand1;
    }
    //</editor-fold>                       

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: textField ">                                   
    /**
     * Returns an initiliazed instance of textField component.
     * @return the initialized component instance
     */
    public TextField getTextField() {
        if (textField == null) {                                 
            // write pre-init user code here
            textField = new TextField("textField", "rohit", 32, TextField.ANY);                                   
            // write post-init user code here
        }                         
        return textField;
    }
    //</editor-fold>                       

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: screenCommand ">                                   
    /**
     * Returns an initiliazed instance of screenCommand component.
     * @return the initialized component instance
     */
    public Command getScreenCommand() {
        if (screenCommand == null) {                                 
            // write pre-init user code here
            screenCommand = new Command("Screen", Command.SCREEN, 0);                                   
            // write post-init user code here
        }                         
        return screenCommand;
    }
    //</editor-fold>                       

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand1 ">                                   
    /**
     * Returns an initiliazed instance of exitCommand1 component.
     * @return the initialized component instance
     */
    public Command getExitCommand1() {
        if (exitCommand1 == null) {                                 
            // write pre-init user code here
            exitCommand1 = new Command("Exit", Command.EXIT, 0);                                   
            // write post-init user code here
        }                         
        return exitCommand1;
    }
    //</editor-fold>                       

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: imageItem ">                                   
    /**
     * Returns an initiliazed instance of imageItem component.
     * @return the initialized component instance
     */
    public ImageItem getImageItem() {
        if (imageItem == null) {                                 
            // write pre-init user code here
            imageItem = new ImageItem("imageItem", getImage1(), ImageItem.LAYOUT_DEFAULT, "<Missing Image>");                                   
            // write post-init user code here
        }                         
        return imageItem;
    }
    //</editor-fold>                       

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: image1 ">                                   
    /**
     * Returns an initiliazed instance of image1 component.
     * @return the initialized component instance
     */
    public Image getImage1() {
        if (image1 == null) {                                 
            // write pre-init user code here
            try {                                                
                image1 = Image.createImage("/Sunset.jpg");
            } catch (java.io.IOException e) {                                              
                e.printStackTrace();
            }                                   
            // write post-init user code here
        }                         
        return image1;
    }
    //</editor-fold>                       

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: okCommand ">                                   
    /**
     * Returns an initiliazed instance of okCommand component.
     * @return the initialized component instance
     */
    public Command getOkCommand() {
        if (okCommand == null) {                                 
            // write pre-init user code here
            okCommand = new Command("show", Command.OK, 0);                                   
            // write post-init user code here
        }                         
        return okCommand;
    }
    //</editor-fold>                       

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: ticker ">                                   
    /**
     * Returns an initiliazed instance of ticker component.
     * @return the initialized component instance
     */
    public Ticker getTicker() {
        if (ticker == null) {                                 
            // write pre-init user code here
            ticker = new Ticker("");                                   
            // write post-init user code here
        }                         
        return ticker;
    }
    //</editor-fold>                       

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: Next ">                                   
    /**
     * Returns an initiliazed instance of Next component.
     * @return the initialized component instance
     */
    public Command getNext() {
        if (Next == null) {                                 
            // write pre-init user code here
            Next = new Command("Next", Command.SCREEN, 0);                                   
            // write post-init user code here
        }                         
        return Next;
    }
    //</editor-fold>                       

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: Send ">                                   
    /**
     * Returns an initiliazed instance of Send component.
     * @return the initialized component instance
     */
    public Command getSend() {
        if (Send == null) {                                 
            // write pre-init user code here
            Send = new Command("Send", Command.SCREEN, 0);                                   
            // write post-init user code here
        }                         
        return Send;
    }
    //</editor-fold>                       

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: Exit ">                                   
    /**
     * Returns an initiliazed instance of Exit component.
     * @return the initialized component instance
     */
    public Command getExit() {
        if (Exit == null) {                                 
            // write pre-init user code here
            Exit = new Command("Exit", Command.SCREEN, 0);                                   
            // write post-init user code here
        }                         
        return Exit;
    }
    //</editor-fold>                       

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: form2 ">                                   
    /**
     * Returns an initiliazed instance of form2 component.
     * @return the initialized component instance
     */
    public Form getForm2() {
        if (form2 == null) {                                 
            // write pre-init user code here
            form2 = new Form("form2");                                    
            form2.addCommand(getSend());
            form2.addCommand(getExit());
            form2.setCommandListener(this);                                  
            // write post-init user code here
        }                         
        return form2;
    }
    //</editor-fold>                       

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: cancelCommand ">                                   
    /**
     * Returns an initiliazed instance of cancelCommand component.
     * @return the initialized component instance
     */
    public Command getCancelCommand() {
        if (cancelCommand == null) {                                 
            // write pre-init user code here
            cancelCommand = new Command("Cancel", Command.CANCEL, 0);                                   
            // write post-init user code here
        }                         
        return cancelCommand;
    }
    //</editor-fold>                       

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: okCommand2 ">                                   
    /**
     * Returns an initiliazed instance of okCommand2 component.
     * @return the initialized component instance
     */
    public Command getOkCommand2() {
        if (okCommand2 == null) {                                 
            // write pre-init user code here
            okCommand2 = new Command("Ok", Command.OK, 0);                                   
            // write post-init user code here
        }                         
        return okCommand2;
    }
    //</editor-fold>                       

    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay () {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable (null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */


    public byte[]load() {

        byte[] imgBytes = null;
        ByteArrayOutputStream baos = null;
        InputStream in = null;
        try {

            baos = new ByteArrayOutputStream();
     	    in = this.getClass().getResourceAsStream("Sunset.jpg"); //this image is inside my mobile application
            byte[] buffer = new byte[1024];
            int n = 0;
            while ((n = in.read(buffer)) != -1) {
                baos.write(buffer, 0, n);
            }

            imgBytes = baos.toByteArray();

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (Exception ex) {
                }
            }
        }

	return imgBytes;
}









    public void send() {
        new Thread(new Runnable() {

            public void run() {

                String imageEncoded = encodeImage(load());
                String format = "jpg";

                //This is my servlet’s URL
                String URL = "http://localhost:8080/Base64ExampleServlet_v2/ImageServlet";

                HttpConnection http = null;
                OutputStream os = null;
                try {
                    //Open HttpConnection using POST
                    http = (HttpConnection) Connector.open(URL);
                    http.setRequestMethod(HttpConnection.POST);
                    //Content-Type is must to pass parameters in POST Request
                    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                    os = http.openOutputStream();



                    imageEncoded = imageEncoded.replace('+', '-');
                    StringBuffer params = new StringBuffer();
                    params.append("imagen" + "=" + imageEncoded);
                    params.append("&" + "format" + "=" + format);
                    System.out.println(params.toString());
                    os.write(params.toString().getBytes());



                    os.flush();
                    System.out.println("Enviado...");
                } catch (IOException ex) {
                    ex.printStackTrace();
                } //whatever happens, close the streams and connections
                finally {
                    if (os != null) {
                        try {
                            os.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }

                    if (http != null) {
                        try {
                            http.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }


    public String encodeImage(byte[] imgBytes) {
        byte[] coded = Base64.encode(imgBytes);
        return new String(coded);
    }



    public void startApp() {
        if (midletPaused) {
            resumeMIDlet ();
        } else {
            initialize ();
            startMIDlet ();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }

}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.