Problem in sending image from applet to servlet

dear friends,
i have a need to send an image from applet to servlet via HttpConnection and getting back that image from applet.
i am struggling with this sice many hours and got tired by searching any post that would help me but haven't got yet.
i tried using this code but it dosent make any execution sit right. i got NPE at ImageIcon.getDescription() line;
at applet side
                 FileDialog fd=new FileDialog(jf,"hi");
                 v=new Vector();
                           FileInputStream fis=new FileInputStream(new File(fd.getDirectory()+fd.getFile()));      
                           byte[] imgbuffer=new byte[fis.available()];
                           ImageIcon imgdata=new ImageIcon(imgbuffer);
                            String strwp ="/UASProject/Storeimage";              
                            URL servletURL = new URL(getCodeBase(),strwp);             
                            HttpURLConnection servletCon = (HttpURLConnection)servletURL.openConnection();       
                            servletCon.setRequestProperty("Content-Type", "application/octet-stream");   
                            ObjectOutputStream oboutStream = new ObjectOutputStream(servletCon.getOutputStream());                     
                            //read back from servlet
                            ObjectInputStream inputStream = new ObjectInputStream(servletCon.getInputStream());
                             v= (Vector)inputStream.readObject();                     
                         //  repaint();
                 }catch(Exception e){e.printStackTrace();}  and this is at servlet side
        try {       
                     Vector v=new Vector();                    
                     ObjectInputStream inputFromjsp = new ObjectInputStream(request.getInputStream());                                      
                      v = (Vector)inputFromjsp.readObject();                                                                                                          
//sending back to applet
                      ObjectOutputStream oboutstream=new ObjectOutputStream(response.getOutputStream());            
               } catch (Exception e) {e.printStackTrace();}  i really need your help. please let me out of this headche
Edited by: san_4u on Nov 24, 2007 1:00 PM

BalusC wrote:
san_4u wrote:
how can i made a HttpClient PostMethod using java applets? as i have experience making request using HttpURLConnection.POST method. ok first of all i am going make a search of this only after i will tell. please be onlineOnce again, see link [3] in my first reply of your former topic.
yeah! i got the related topic at please look it, i am reading it right now and expecting to be reliable for me.
well what i got, when request made by html code(stated above) then all the form fields and file data mixed as binary data and available in HttpServletRequest.getinputstream. and at servlet side we have to use a mutipart parser of DiskFileItemFactory class that automatically parse the file data and return a FileItem object cotaing the actual file data,right?.You can also setup the MultipartFilter in your environment and don't >care about it further. Uploaded files will be available as request attributes in the the multipartfilter class file available in jar files(that u suggested to add in yours article) so that i can use it directly? one more thing the import org.apache.commons.httpclient package is not available in these jar files, so where can got it from?
one mere question..
i looked somewhere that when we request for a file from webserver using web browser then there is a server that process our request and after retrieving that file from database it sends back as response.
now i confused that, wheather these webservers are like apache tomcat, IBM's webspher etc those processes these request or there is a unique server that always turned on and process all the request?
because, suppose in an orgnisation made it's website using its own server then, in fact, all the time it will not turned on its server or yes it will? and a user can make a search for kind of information about this orgnisation at any time.
hopes, you will have understand my quary, then please let me know the actual process
Edited by: san_4u on Nov 25, 2007 11:25 AM

Similar Messages

  • Problem in Sending email from Reports Queue Manager

    I am getting problem in sending email from reports queue manager.
    It says that error in logging to mail server.
    If any body knows the sol then pl help me out.

    I am getting problem in sending email from reports queue manager.
    It says that error in logging to mail server.
    If any body knows the sol then pl help me out.

  • I can not send my Note through email and it used to work. The same problem to send picture from iPhone message

    Can't send Notes through email and it used to work. The same problem of sending picture from iPhone message. Did the reset twice but still not working

    Try a reset:
    Hold the Sleep and Home button down for about 10 second until you see the Apple logo.

  • I am facing a Problem with reading images from database

    Hi everybody..
    any help will be most appreciated, I am facing problem with reading images from database. I am pasting my code... 
                    string connect = "datasource = localhost; port = 3306; username = root; password = ;"; 
                    MySqlConnection conn = new MySqlConnection(connect); // creating connecting string
                    MySqlCommand sda = new MySqlCommand(@"select * from management.add_products ", conn); //creating query
                    MySqlDataReader reader; 
                        conn.Open(); // Opening Connection
                        reader = sda.ExecuteReader(); // Executing my Query..
                        while (reader.Read())
                            byte[] imgg = (byte[])(reader["Picture"]);
                            if (imgg == null)
                                pc1.Image = null;
                                MemoryStream mstream = new MemoryStream(imgg);
                                pc1.Image = System.Drawing.Image.FromStream(mstream);
    It says Parameter not Valid... i am reading all the images from database

    I agree with Viorel. You are getting the error because the format of the data is incorrect probably because the data was modify. It may not be the reading of the database the is incorrect, but the application that wrote the data into the database. You need
    to compare the imgg array data with the data before it was written to the database to see if the data matches.  I usually start by comparing the number of bytes which is easier to check then compare the actual to isolate which function is changing the
    byte count.
    An image is binary data.  The standard VS methods for reading and writing data (usually stream classes) default to ASCII encoding which will corrupt binary data.  The solution usually is to use UTF8 encoding instead of the default ascii encoding. 
    Ascii encoding with stream often aligns the data and adds extra null bytes to the end of the data which can produce these type errors.

  • Retrieve multiple images from database to servlet

    Hi there,
    I try to retrieve more than one images from database to Servlet/JSP . However, I get only one images in the result set. Here is my code. Please Help .
    How do I display more than one images ( multiple rows ) from database to Servlet ?.
    When I retrieve, I got 3 rows of binary data, but I don't know how to display it on the Servlet/JSP pages.
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.lang.*;
    import java.sql.*;
    import com.sybase.jdbcx.*;
    public class RetrievePhoto extends HttpServlet {
    static ResultSet rs;
    static CallableStatement NGSstmt = null;
    static Connection NGScon = null;
    static SybDriver _driver = null;
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws
    ServletException, IOException {
    ServletOutputStream os = res.getOutputStream();
    String driver = ""
    String URL = "";
    String Host = "";
    String UN = ""; //assign your username here
    String PW = ""; //assign your password here
    try {
    Class c = Class.forName( driver );
    _driver = (SybDriver) c.newInstance();
    DriverManager.registerDriver( (SybDriver) _driver );
    NGScon = DriverManager.getConnection( URL + Host, UN, PW );
    } catch ( SQLException e ) {
    os.println( "Unable to load the Sybase JDBC driver. " + e.toString() );
    } catch (java.lang.Exception ex) {
    // Got some other type of exception. Dump it.
    os.println("Exception - java lang " + ex.getMessage() );
    String PID = req.getParameter("PID"); //passing parameters from Servlet
    try {
    String SQLcmd = "{call RET_PHOTO_BY_PID(?)}";
    NGSstmt = NGScon.prepareCall( SQLcmd );
    //execute the query
    synchronized (NGSIDBstmt)
    NGSstmt.setString(1, PID); //passing parameter to store procedure
    rs = NGSstmt.executeQuery();
    byte[] stuff = new byte[1024];
    int bytesRead = 0;
    InputStream is = null;
    // Get the first row
    while( ) {
    is = rs.getBinaryStream("PHOTO");
    for (int i=0;; i++) {
    bytesRead =;
    if ( bytesRead == -1 ) break;
    os.close(); //close outputstream
    } catch ( SQLException sqle) {
    os.println("Error in SQL2Exception" + sqle.getMessage());

    When I retrieve, I got 3 rows of binary data, but I don't know how to display it on the Servlet/JSP pages.I will pick this bit of your post, because you seemed to have several partly-overlapping questions.
    You are going about this wrong. You need to decide what your HTML will look like before you start writing servlet code. In this case you want to have something like a table, with an image in each row, right? Now what does the HTML for that look like? It's a <table> element, and so on, but what about the images? Well this is HTML, so it can't contain the binary images. It has to contains links to the images, and the browser will download the image from each of those links and put all of the downloads together into the page it displays.
    That means you can't do it all with one servlet. You need a main servlet that generates the HTML, with the <table> element and the links to the images. Probably you need some DB calls here to find out how many images you're going to have, but you don't need to get them in this servlet. You just need to generate a link for each of them.
    Then you need a second servlet that gets an image. It's going to get a single row from the DB and return the binary image you read from that row. Make sure to use "image/jpg" or whatever's appropriate instead of "text/html" in your response's content type here.
    I will leave you to carry on from here. First step is to design the HTML that your main servlet will produce; remember that the links it generates need to carry enough information for the second servlet to be able to find the right image in the DB.

  • Problem with sending mail from SAP (ECC6.0)

    Hi guys!!
    I am facing problem in sending email from SAP to outlook.
    I've checked SICF and SCOT configuration and they are same as my other server thorugh which i am able to send the mail.
    I use SBWP to send the mail. after i send i do not get any error message, and when i check it in outbox, there is a yellow triangle in the status which means "send process still running" . so the sending mail is taking hours. i've set the frequesncy of my B/G job RSCONN01 to 10 minutes. i checked and this job is running successfully every 10 minutes.
    Please suggest what could be the possible reason and what can i do to solve this issue.
    Sheetal Sharma

    First of all ask your IT (Exhchange) guy to check port number 25 is open or not for communincation, if not open ask him to open.
    you can check this yourself by doing TELNET
    steps to do telnet :
    logon to your application server,
    go to command prompt
    and type  TELNET <IP address of email server> 25
    If it prompts some message like this
    " Microsoft ESMTP MAIL Service, Version: 6.0.3790.18 30 ready at  Mon, 16 Jun 2008 16:25:41 +0300. "
    then it means your port 25 is open for communication.

  • Problem while sending seriailized  object from applet to servlet

    Hi I m having Object communication between Applet and Servlet.
    I m getting error stack trace as
         at$PeekInputStream.readFully(Unknown Source)
         at$BlockDataInputStream.readShort(Unknown Source)
    at Source)
         at<init>(Unknown Source)
    at the line
    ObjectInputStream ois = new ObjectInputStream(conn.getInputStream());
    thanks in advance
    the whole code is as follows....
    public Serializable write(Serializable obj) throws IOException,ClassNotFoundException{
              URLConnection conn = serverURL.openConnection();
              conn.setRequestProperty("Content-Type", "java-internal/"+obj.getClass().getName());
              ObjectOutputStream oos= null;
              oos = new ObjectOutputStream(
                   catch(Exception ee){
                        return the reponse to the client
                   ObjectInputStream ois=null;
    \\this is the line where i m getting the error               
    ois = new ObjectInputStream(conn.getInputStream());
                             return (Serializable)ois.readObject();
                        catch(Exception ee){
                                            System.out.println("Error in Object Client inputstream ");
                                            return null;

    Did anyone find a fix to this problem. I am having a similiar problem. Sometimes I receive an EOFException and othertimes I don't. When I do receive an EOFException I check for available() in the stream and it appears 0 bytes were sent to the Servlet from the Applet.
    I am always open to produce this problem when I use File->New in IE my applet loads on the new page.. and then I navigate to a JSP sitting on the same application server. When I go to the Applet on the initial page and try to send an object to the server I get an EOFException. No idea!

  • Sending a file from Applet to servlet HELP me Please

    Sorry, i have the problem this is my code Applet & Servlet but it seems working asynchronously if you have some ideas please reply me i send bytes on outputstream but the inputstream of servlet receive nothing bytes but write my system.out.print on screen server:
    URL servletURL = new URL(codebase, "/InviaFile/servlet/Ricevi");
    HttpURLConnection urlConnection = (HttpURLConnection) servletURL.openConnection();
    urlConnection.setRequestProperty("Content-Type", "application/octet-stream");
    urlConnection.setRequestProperty("Content-length", String.valueOf(100));
    if(urlConnection.HTTP_BAD_REQUEST == HttpURLConnection.HTTP_BAD_REQUEST){
    /*System.out.println("Cattiva Richiesta: "+urlConnection.getContentEncoding());
    System.out.println("Tipo di metodo: "+urlConnection.getRequestMethod());
    System.out.println("Tipo di Risposta: "+urlConnection.getResponseCode());
    System.out.println("Tipo di messaggio: "+urlConnection.getResponseMessage());
    System.out.println("Tipo di contenuto: "+urlConnection.getContentType());
    System.out.println("Tipo di lunghezza contenuto: "+urlConnection.getContentLength());
    System.out.println("Tipo di doinput: "+urlConnection.getDoInput());
    System.out.println("Tipo di doouput: "+urlConnection.getDoOutput());
    System.out.println("Tipo di URL: "+urlConnection.getURL());
    System.out.println("Tipo di propriet� richiesta: "+urlConnection.getRequestProperty("Content-Type"));
    System.out.println("Entra if");
    DataOutputStream dout = new DataOutputStream(urlConnection.getOutputStream());
    InputStream is = urlConnection.getInputStream();
    if(ritornaFile("C:/Ms.tif", dout))System.out.println("Finita lettura");
    System.out.println("Fine Applet");
    }catch(Exception e) { System.err.println(e.getMessage());e.printStackTrace();}
    public boolean ritornaFile(String file, OutputStream ots)throws Exception{
    FileInputStream f = null;
    f = new FileInputStream(file);
    byte[] buf = new byte[4 * 1024];
    int byteLetti;
    while((byteLetti = != -1){ots.writeByte(buf, 0, byteLetti);ots.flush();
    while((byteLetti = != -1){ots.write(byteLetti);ots.flush();
    System.out.println("byteLetti= "+byteLetti);
    return true;
    }catch(Exception ex){
    return false;
    if(f != null)f.close();
    HttpSession ses = request.getSession(true);
    System.out.println("Passa servlet "+request.getMethod());
    System.out.println("Passa servlet "+ses.getId());
    ServletInputStream servletinputstream = request.getInputStream();
    DataInputStream dis = new DataInputStream(request.getInputStream());
    int c = dis.available();
    //ServletOutputStream servletoutputstream
    System.out.println("URI= "+request.getRequestURI());
    System.out.println("pathTranslated: "+request.getPathTranslated());
    System.out.println("RemoteUser: "+request.getRemoteUser());
    System.out.println("UserInRole: "+String.valueOf(request.isUserInRole("")));
    System.out.println("pathInfo: "+request.getPathInfo());
    System.out.println("Protocollo: "+request.getProtocol());
    int i = request.getContentLength();
    System.out.println("i: "+i);
    ritornaFile(servletinputstream, "C:"+File.separator+"Pluto.tif");
    System.out.println("GetMimeType= "+getServletContext().getMimeType("Ms.tif"));
    InputStream is = request.getInputStream();
    int in = is.available();
    System.out.println("Legge dallo stream in="+in);
    DataInputStream diss = new DataInputStream(servletinputstream);
    int ins =;
    System.out.println("Legge dallo stream ins="+ins);
    int disins = diss.available();
    System.out.println("Legge dallo stream disins="+disins);
    System.out.println("Fine Servlet");
    catch(Exception exception) {
    System.out.println("IOException occured in the Server: " + exception.getMessage());exception.printStackTrace();
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, {
    processRequest(request, response);
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, {
    processRequest(request, response);
    /** Returns a short description of the servlet.
    public String getServletInfo() {
    return "Short description";
    public void ritornaFile(InputStream its, String fileDest )throws Exception{
    FileOutputStream f = null;
    f = new FileOutputStream(fileDest);
    byte[] buf = new byte[2 * 1024];
    int byteLetti;
    while((byteLetti = != -1){
    f.write(buf, 0, byteLetti);
    }catch(Exception ex){
    if(f != null)f.close();

    Hi all,
    Can anyone help me.I am trying to send an audio file from a applet to servlet with HTTP method(no raw sockets), also the servlet shld be able to save the file on the server.Any suggestions welcome.USing audiostream class from javax.sound.sampled.
    The part of applet code which calls servlet is :
    URL url = new URL("http://" + host + "/" + context + "/servlet/UserUpdateWorkLogAudio?userid=" + userId.replace(' ', '+') + "&FileName=" + filename.replace(' ', '+'));
    URLConnection myConnection = url.openConnection();
    urlConnection.setRequestProperty("Content-Type", "application/octet-stream");
    out = new BufferedOutputStream(myConnection.getOutputStream());
    AudioSystem.write(audioInputStream, fileType,out); // IS THIS RIGHT APPROACH?
    ************************end of applet code**********************
    ************************servlet code******************************
    {BufferedInputStream in = new BufferedInputStream(request.getInputStream());
    ????????What code shld i write here to get the audio file stream
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filename));

  • Writing Image files from Applet to Servlet

    How to write ImageFiles from an Applet to a Servlet?
    I draw a image on a JComponent in Applet and wanted to save the image file in the server.
    I am unable to write an Image Object to the Servlet as the BufferedImage class is not serialized.
    I tried writing the image to the Servlet output stream and tried reading the data in the servlet and writing the data to a jpg file.
    But the files is not being written as proper jpeg file.
    Any help would be great.

    I get the following exception below when i try to write a Serialized object from an applet to the servlet.
    I copied the serialized class jar file to the tomcat webserver lib folder.
    The serialized class has a BufferedImage object.
    Serialized Class Code
    public class SerializedImage implements Serializable{
         private BufferedImage im = null;
         public SerializedImage() {
         public BufferedImage getSerializedObject() {
              return im;
         public void setSerializedObject((BufferedImage im) {
     = im;
         private BufferedImage fromByteArray(byte[] imagebytes) {
              try {
                   if (imagebytes != null && (imagebytes.length > 0)) {
                        BufferedImage im = ByteArrayInputStream(imagebytes));
                        return im;
                   return null;
              } catch (IOException e) {
                   throw new IllegalArgumentException(e.toString());
         private byte[] toByteArray(BufferedImage o) {
              if(o != null) {
                   BufferedImage image = (BufferedImage)o;
                   ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
                   try {
                        ImageIO.write(image, "jpg", baos);
                   } catch (IOException e) {
                        throw new IllegalStateException(e.toString());
                   byte[] b = baos.toByteArray();
                   return b;
              return new byte[0];
         private void writeObject( out)
         throws IOException {
              byte[] b = toByteArray(im);
         private void readObject( in)
         throws IOException, ClassNotFoundException {
              int length = in.readInt();
              byte[] b = new byte[length];
              im = fromByteArray(b);
    Exception : unexpected block data
    Is there any thing that i am missing or doing wrong?

  • Sending different types of data from applet to servlet

    I am writing an applet that uploads a file to a servlet. I can send the file to the servlet just fine.
    Applet Side
    1. open a URLConnection
    2. open a DataOutputStream
    3. write the file to the DataOutputStream
    Servlet Side:
    1. open a ServletInputStream from the HttpServletRequest
    2. write the bytes to a file
    This is all fine.
    However, I need to upload the filename (a String) with the file. How do I do this? I can't send the filename over as a String from the applet using the same DataOutputStream. right? This would corrupt the file that i am sending as the servlet wouldn't know that the difference between the filename and the actual contents of the file.
    Is there some property I can set in the urlconnection that gets passed to the request variable? i.e. URLConnection.setProperty ("filename", foo.txt) and then on the servlet side do this: String filename = eq.getProperty ("filename")
    Thank you for the help

    If all the additional data you want to send to server are textual or numaric data about the file (which is in the body of the request)
    Use those information as additional http headers.
    And read those header information from the servlet request object at the server side
    URL u = new URL("your url");
    HttpURLConnection c = (HttpURLConnection)u.openConnection();
    c.addRequestProperty("x-application-file-name","name of the file");
    c.addRequestProperty("x-application-file-size","size of the file");
    //then open the stream and write the data to the request body
    //             At server side         //
    String name = request.getHeader("x-application-file-name");
    long size= Long.parseLong(request.getHeader("x-application-file-size"));

  • How to send image from web start application to my servlet

    Hi all,
    I have uploaded image in my web start application and now i want to send that image to my servlet. I have created URL connection and using output stream i am able to send data in String as well as numeric format but i have to send image also.
    please help.
    thanks in advance.

    I have done it. contact [email protected]

  • Saving images from applet back to the host

    I am trying to save an image (or a buffered image) from an applet back to its original host . Is there a way to do this without using a servlet at the server's end?
    An earliest response would be appreciated.
    Thanks in advance.

    Thanks to all of you for your help. Your replies have been helpful to me.
    Atlast I'm done with my problem. I am able to write my image to the host.
    I have converted the Image(buffered image) into a byte stream
    converted the stream to byte array:
    byte[] b=bos.toByteArray();
    and used HttpURLConnection to write the byte array to the host.
    Thank you.

  • Problem creating an image from a remote url

    I am creating a servlet which does the following:
    1. retrieves an image from a remote url
    2. resizes the image
    3. sends the image to the client.
    The servlet works fine when I run it on my PC, but when I run it on the server, it doesn't. Here's the problematic code
        private Image getRemoteImage(String imageUrl) throws Exception {
            System.err.println("in getRemoteImage()");
            if (!imageUrl.startsWith("http://")) imageUrl = "http://" + imageUrl;
            URL u = new URL(imageUrl);
            System.err.println("imageUrl: " + imageUrl);
            HttpURLConnection huc = (HttpURLConnection) u.openConnection();
            System.err.println("Getting DataInputStream...");
            DataInputStream in = new DataInputStream(u.openStream());
            //DataInputStream in = new DataInputStream(huc.getInputStream());
            int numBytes = huc.getContentLength(); //1063
            System.err.println("numBytes: " + numBytes);
            byte[] imageBytes = new byte[numBytes];
            System.err.println("reading fully...");
            System.err.println("creating imageIcon");
            ImageIcon imageIcon = new ImageIcon(imageBytes);  //   <-- problem here
            System.err.println("** THIS LINE IS NOT REACHED **");
            System.err.println("creating image");
            Image image = imageIcon.getImage();
            System.err.println("returning image");
            return image;
        }When I access the servlet with FF, the browser reports:
    The image �<my servlet url>� cannot be displayed, because it contains errors.
    When I access the servlet with IE, I get:
    Apache Tomcat/4.0.3 - HTTP Status 500 - Internal Server Error
    type Exception report
    message Internal Server Error
    description The server encountered an internal error (Internal Server Error) that prevented it from fulfilling this request.
    javax.servlet.ServletException: Servlet execution threw an exception
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(
         at org.apache.catalina.core.StandardWrapperValve.invoke(
         at org.apache.catalina.core.StandardPipeline.invokeNext(
         at org.apache.catalina.core.StandardPipeline.invoke(
         at org.apache.catalina.core.ContainerBase.invoke(
         at org.apache.catalina.core.StandardContextValve.invoke(
         at org.apache.catalina.core.StandardPipeline.invokeNext(
         at org.apache.catalina.core.StandardPipeline.invoke(
         at org.apache.catalina.core.ContainerBase.invoke(
         at org.apache.catalina.core.StandardContext.invoke(
         at org.apache.catalina.core.StandardHostValve.invoke(
         at org.apache.catalina.core.StandardPipeline.invokeNext(
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(
         at org.apache.catalina.core.StandardPipeline.invokeNext(
         at org.apache.catalina.valves.ErrorReportValve.invoke(
         at org.apache.catalina.core.StandardPipeline.invokeNext(
         at org.apache.catalina.valves.AccessLogValve.invoke(
         at org.apache.catalina.core.StandardPipeline.invokeNext(
         at org.apache.catalina.core.StandardPipeline.invoke(
         at org.apache.catalina.core.ContainerBase.invoke(
         at org.apache.catalina.core.StandardEngineValve.invoke(
         at org.apache.catalina.core.StandardPipeline.invokeNext(
         at org.apache.catalina.core.StandardPipeline.invoke(
         at org.apache.catalina.core.ContainerBase.invoke(
         at org.apache.ajp.tomcat4.Ajp13Processor.process(
    root cause
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(
         at java.awt.Toolkit$
         at Method)
         at java.awt.Toolkit.getDefaultToolkit(
         at javax.swing.ImageIcon.(
         at myservlets.GetImage.getRemoteImage(
         at myservlets.GetImage.processRequest(
         at myservlets.GetImage.doGet(
         at javax.servlet.http.HttpServlet.service(
         at javax.servlet.http.HttpServlet.service(
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(
         at org.apache.catalina.core.StandardWrapperValve.invoke(
         at org.apache.catalina.core.StandardPipeline.invokeNext(
         at org.apache.catalina.core.StandardPipeline.invoke(
         at org.apache.catalina.core.ContainerBase.invoke(
         at org.apache.catalina.core.StandardContextValve.invoke(
         at org.apache.catalina.core.StandardPipeline.invokeNext(
         at org.apache.catalina.core.StandardPipeline.invoke(
         at org.apache.catalina.core.ContainerBase.invoke(
         at org.apache.catalina.core.StandardContext.invoke(
         at org.apache.catalina.core.StandardHostValve.invoke(
         at org.apache.catalina.core.StandardPipeline.invokeNext(
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(
         at org.apache.catalina.core.StandardPipeline.invokeNext(
         at org.apache.catalina.valves.ErrorReportValve.invoke(
         at org.apache.catalina.core.StandardPipeline.invokeNext(
         at org.apache.catalina.valves.AccessLogValve.invoke(
         at org.apache.catalina.core.StandardPipeline.invokeNext(
         at org.apache.catalina.core.StandardPipeline.invoke(
         at org.apache.catalina.core.ContainerBase.invoke(
         at org.apache.catalina.core.StandardEngineValve.invoke(
         at org.apache.catalina.core.StandardPipeline.invokeNext(
         at org.apache.catalina.core.StandardPipeline.invoke(
         at org.apache.catalina.core.ContainerBase.invoke(
         at org.apache.ajp.tomcat4.Ajp13Processor.process(
    Any ideas?

    Cheers rebol.
    I've tried that (along with all other kinds of techniques I never knew existed). I think it might be a problem with the Tomcat setup - it may need to run headless (sounds a bit severe!...).

  • Pass byte[] from applet to servlet

    I have an application that allows users to copy an image from the system clipboard into a frame. What I would like to be able to do, is save that image into a database (db2 on as/400). In order to do that, I try to send the image, which I turned into a byte[] in order to easily insert into the database, from the applet to the servlet using streams (no actual file io), but the image always comes up null when I pass it to the servlet. What am I doing wrong? The image gets copied and drawn from the clipboard just fine, but I can't send it to the servlet. I only included the part of the servlet that tries to retreive the byte array. I know the applet code is a little long, but I figured it might be of interest to someone. Please help!
    Here's the code for the applet:
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.awt.datatransfer.*;
    import javax.swing.ImageIcon;
    import java.util.*;
    import java.awt.image.*;
    public class PicApp extends Applet implements ClipboardOwner
    PrintWriter opWriter = null;
    private Button cmdPaste = new Button();
    private ImageControl destinationImage = new ImageControl ();
    private BorderLayout defaultLayout = new BorderLayout ();
    public Image tempImage = null;
    public ImageIcon transferImage = null;
    private String webServerStr = "";
    private String hostName = null;
    private int port = 80;
    private String servletPath = null;
    Clipboard clipboard;
    //the byte array I try to pass
    public byte[] passed = null;
    public String passedAction = null;
    public void init()
    opWriter = new PrintWriter( new BufferedWriter( new FileWriter( "pictureDetails.txt" ) ) );
    catch(Exception e)
    hostName = getParameter("HostName");
    servletPath = getParameter("ServletPath");
    passedAction = getParameter("Action");
    this.setLayout (defaultLayout);
    cmdPaste.setLabel("Paste Image from Clipboard");
    this.add (cmdPaste, BorderLayout.SOUTH);
    this.add (destinationImage, BorderLayout.NORTH);
    //add action listener
    cmdPaste.addActionListener (new cmdPasteActionListener ());
    //initialize the clipboard
    clipboard = getToolkit().getSystemClipboard();
    // get the host name and port of the applet's web server
    opWriter.println("Picutre Applet Details\n");
    URL hostURL = getCodeBase();
    opWriter.println("hostURL = " + hostURL.toString() + "\n");
    hostName = hostURL.getHost();
    opWriter.println("hostIP = " + hostName + "\n");
    port = hostURL.getPort();
    opWriter.println("port = " + port + "\n");
    if (port == -1)
    port = 80;
    if(passedAction == "" || passedAction == null)
    webServerStr = "http://" + hostName + ":" + port + servletPath;
    opWriter.println("Web String full = " + webServerStr);
    webServerStr = "http://" + hostName + ":" + port + servletPath + "?act=" + passedAction;
    opWriter.println("Web String full = " + webServerStr);
    catch(Exception e)
    class cmdPasteActionListener implements ActionListener
    public void actionPerformed (ActionEvent event)
    Transferable clipboardContent = clipboard.getContents(this);
    //Transferable clipboardContent = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
    if ((clipboardContent != null) && (clipboardContent.isDataFlavorSupported(DataFlavor.imageFlavor)))
    //display Image
    tempImage = (Image)clipboardContent.getTransferData(DataFlavor.imageFlavor);
    int width = (new ImageIcon(tempImage).getIconWidth());
    int height = (new ImageIcon(tempImage).getIconHeight());
    PixelGrabber pg = new PixelGrabber(tempImage, 0, 0, width, height, true);
    passed = new byte[width*height];
    passed = (byte[])pg.getPixels();
    //send Image
    catch (UnsupportedFlavorException e)
    catch (IOException e)
    }//end of if
    else if(clipboardContent == null)
    }//end of method
    }//end of inner class
    public PicApp()
    public void lostOwnership (Clipboard parClipboard, Transferable parTransferable)
    System.out.println("Lost ownership of clipboard");
    protected void ProcessPicture()
    // connect to the servlet
    URL servletURL = new URL( webServerStr );
    //URLConnection servletConnection = servletURL.openConnection();
    HttpURLConnection servletConnection =(HttpURLConnection)servletURL.openConnection();
    // inform the connection that we will send output and accept input
    // Don't used a cached version of URL connection.
    servletConnection.setUseCaches (false);
    // Specify the content type that we will send binary data
    servletConnection.setRequestProperty("Content-Type", "application/octet-stream");
    // send the image object to the servlet using serialization
    // now, let's read the response from the servlet.
    // this is simply a confirmation string
    catch (Exception e)
    protected void readServletResponse(URLConnection servletConnection)
    BufferedReader inFromServlet = null;
    // now, let's read the response from the servlet.
    // this is simply a confirmation string
    inFromServlet = new BufferedReader(new InputStreamReader(servletConnection.getInputStream()));
    String str;
    while (null != ((str = inFromServlet.readLine())))
    System.out.println("Reading servlet response: " + str);
    catch (IOException e)
    protected void sendImageToServlet(URLConnection servletConnection)
    ObjectOutputStream outputToServlet = null;
    // send the image object to the servlet using serialization
    outputToServlet = new ObjectOutputStream(servletConnection.getOutputStream());
    //check size of image
    // write objectt
    catch (IOException e)
    public void performTask(HttpServletRequest request, HttpServletResponse response)
    ObjectInputStream inputFromApplet = null;
    byte[] ImageFromApplet = null;
    PrintWriter out = null;
    BufferedReader inTest = null;
    // get an input stream from the applet
    inputFromApplet = new ObjectInputStream(request.getInputStream());
    // read the serialized imageIcon data from applet
    ImageFromApplet = (byte[])inputFromApplet.readObject();
    catch(Exception e)
    // handle exception
    byte[] transferImage = ImageFromApplet;
    if(transferImage == null)
    System.out.println("Image passed is empty!");

    I read your code. I believe you are trying to send the byte array with the wrong outputStream.write method. For a byte[] I have successfully used the form, servletOut.write(byteArray, 0, byteArray.length). You have to tell the receiver how much data will be sent to it so it knows when to stop read in the data.
    _url = new;
    //Attempt to connect to the host connection = _url.openConnection();
    // Initialize the connection
    connection.setRequestProperty("Content-type", "application/octet-stream");
    BufferedInputStream fileInputStream = new BufferedInputStream(fIS);
    int nBytesAvailable = fileInputStream.available();
    byte byteArray[] = new byte[nBytesAvailable];, 0, nBytesAvailable);
    // send data to servlet, get outstream, write data, flush, close.
    DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
    outStream.write(byteArray, 0, nBytesAvailable);

  • Problem in sending images

    Hi All,
    I have a problem in sending HTML mail with images.I am able to get the image in my mail if i place the image part and the html part in two different tables I am able to get the image along with the html message but if i use the following code i.e using single table i am not able to get the image someone plase help me to get this done and tell me where am i going wrong?
    Properties props = System.getProperties();
                    props.put("", smtpServer);
                    Session session = Session.getDefaultInstance(props, null);
                     Message message = new MimeMessage(session);
                   message.setFrom(new InternetAddress(from));
                    message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to, false));
                   message.setSentDate(new Date());
                    MimeBodyPart messageBodyPart = new MimeBodyPart();
              MimeBodyPart messageBodyPart1 = new MimeBodyPart();
              MimeBodyPart messageBodyPart2 = new MimeBodyPart();
    StringBuffer msgStrBuf = new StringBuffer();
    msgStrBuf.append("<html><head></head> <body><table  width=\"640\" align=\"center\"  height=\"293\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" bgcolor=\"#D3D3D3\" ><tr><td><img src=\"cid1:image1\" width=\"640\" height=\"92\"></td></tr>");
    DataSource fds1 = new FileDataSource("webimages\\sampleimage.jpg");
    messageBodyPart.setDataHandler(new DataHandler(fds1));
    String headerbody = "";
    msgStrBuf.append("<tr><td width=\"640\" align=\"center\"   bgcolor=\"#E6E6E6\" height=\"50\" valign=\"top\"><font size=\"2\" color=\"#4C4C4C\" face=\" Arial,Verdana, Helvetica, sans-serif\">����Dear "+locUserName+","+"<br><br>����"+"Here is the updated status report on your project.</font></td></tr>"+"  <tr> <td bgcolor=\"#E6E6E6\" height=\"100\" align=\"center\" valign=\"middle\">  <table width=\"95%\" height=\"100\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" bgcolor=\"4C4C4C\" >" +"<tr> <td width=\"200\" align=\"left\" valign=\"middle\"><strong><font  size=\"2\" face=\" Arial,Verdana, Helvetica, sans-serif\" color=\"#FFFFFF\">��PROJECT:</font></strong></td><td><font  size=\"2\" face=\" Arial,Verdana, Helvetica, sans-serif\" color=\"#FFFFFF\"><strong>"+getProjectName+"</strong></font></td></tr>"+"   <tr> <td  width=\"200\" align=\"left\" valign=\"middle\"><font  size=\"2\" face=\" Arial,Verdana, Helvetica, sans-serif\" color=\"#FFFFFF\"><strong>��LAST UPDATE:</strong></font></td><td><font  size=\"2\" face=\" Arial,Verdana, Helvetica, sans-serif\" color=\"#FFFFFF\"><strong>"+concatTime+"</strong></font></td></tr></tr></table></td></tr> "  );
    msgStrBuf.append("<tr> <td  bgcolor=\"#E6E6E6\" height=\"50\" valign=\"middle\"><font size=\"2\" color=\"#4C4C4C\" face=\" Arial,Verdana, Helvetica, sans-serif\">����" +"In case you have any questions, please send an email to <a href=\"mailto: </a>. Our customer <br>����service representative will contact you to address any  concerns. ");
    msgStrBuf.append("<br><br>����Thank You,<br> ���.</font></td></tr>");
    msgStrBuf.append("<tr><td  bgcolor=\"#E6E6E6\" height=\"100\" valign=\"top\"> <br><hr><font color=\"#666666\" size=\"-6\" face=\" Arial,Verdana, Helvetica, sans-serif\">����This is an automatically generated email. Please do not reply to this. If you need further information, contact the email address <br>����given above.<br>����If you wish to change your contact email address, please log in to follow the link and modify your<br>����preferences. You can also change the frequency of email updates in the project settings link.</font></td></tr>");
    headerbody = msgStrBuf.toString();
    // Part two is attachment
    String mailingFileId = "";
    mailingFileId = "XL Data/"+getProjectID+".xls";
    mailingFileId = "GPXL Data/"+getProjectName+".xls";
    System.out.println("mailingFileId :"+mailingFileId);
    System.out.println("locGroupClass :"+locGroupClass);
    String mailingFileNAme = getProjectName+".xls";
    DataSource source = new FileDataSource(mailingFileId);
    messageBodyPart2.setDataHandler(new DataHandler(source));
    messageBodyPart2.setFileName( mailingFileNAme);
    // Put parts in message
                    System.out.println("Message sent OK.");
                  } catch (Exception ex)
                        }Message was edited by:

    messageBodyPart.setHeader("Content-ID1","<image1>");The name of the header is "Content-ID", not "Content-ID1".
    Of course, if you used the setContentID method on MimeBodyPart,
    the compiler would find this error for you.

Maybe you are looking for