Share on Google+Share on Google+

Teja varma
How to upload image to server in j2me by multipart/form-data?
1 Answer(s)      5 years and 6 months ago
Posted in : Java Beginners

Hi,

I need upload data to java server from j2me 1.Two text messages and 3 capture images to server. 2.As java server is already designed, as we want to send data in multi part form data. 3.As write code to upload text and image.As it is working fine while we send data to server from emulator.But by uploading same code from mobile it is showing exception.I am using mobile to upload in Samsung S5620 Monte. 4.I getting exception

org.apache.commons.fileupload.FileUploadException: Processing of ``multipart/form- data request failed. Stream ended unexpectedly at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadB ase.java:384) at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest( ServletFileUpload.java:116) at org.apache.jsp.photojsp.jspService(photo_jsp.java:119) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper .java:384) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:3 20) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke (StandardWrapperValve.java:228) at org.apache.catalina.core.StandardContextValve.invoke (StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke (StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke (ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke (StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service (CoyoteAdapter.java:216) at org.apache.coyote.http11.Http11Processor.process (Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol $Http11ConnectionHandler.process(Http11Protocol.java:634) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run (JIoEndpoint.java:445) at java.lang.Thread.run(Unknown Source)

From J2me I am using code to upload image to server is. HttpConnection conn = null; OutputStream os = null; // InputStream is = null;

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

  //  String postData = "";

    InputStream imgIs = getClass().getResourceAsStream(FILE);
    byte []imgData = new byte[imgIs.available()];
    imgIs.read(imgData);

    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------4664151417711");

    os = conn.openOutputStream(); 
   // os.write(message1.getBytes()); 
 // For First Image uploading

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

      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("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){}
}

on serside we use the code:

FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory);

boolean isMultipart = ServletFileUpload.isMultipartContent(request);

if(isMultipart) {

   **List items = upload.parseRequest(request);//I am getting exception here**


      Iterator iterator = items.iterator();
      while(iterator.hasNext())
      {
             String fieldName = "";
              String fieldValue=""; 
              String fileName = ""; 
               FileItem fileItem=(FileItem)iterator.next();
               System.out.println(fileItem.isFormField());
if (fileItem.isFormField())
{
     fieldName = fileItem.getFieldName();
     fieldValue = fileItem.getString("UTF-8").trim();

     if(fieldName.equals("photo"))
     {
         if(fieldValue!=null && fieldValue!="")
         {
              photo = fieldValue;
              System.out.println(photo);
         }
     }
}           
else

 try
 {
     if(fileItem != null)
     {
         fileName = applicationNumber+"_"+fileItem.getName();
         fieldName = fileItem.getFieldName();
        System.out.println("applicationNumber="+fileName);
     }
     if(fieldName.equals("photo"))  
    {       
       String x=fileName;
        if(x.indexOf("/")!=-1)
        {
             uploadStr = x.substring(0,x.lastIndexOf("/") );
             UploadFile = x.substring(x.lastIndexOf("/")+1,x.length() );
        }
         long sizeInBytes = fileItem.getSize();
         String applicationURL = "C:/Program Files/
           Apache Software Foundation/Tomcat 6.0/webapps/apply_smart/applications";
 StringTokenizer stringTokenizer = new StringTokenizer(UploadFile,"\\");
            int  count=stringTokenizer.countTokens();
             for(int i=1;i<=count;i++)
             {
                      String token=stringTokenizer.nextToken();
                       if(i==count)
                      {
                           audioFileName=token;
                      }
               }
              applicationURL = applicationURL;
              System.out.println("Path="+applicationURL);
              String[] filePath = fileName.split("/");
uploadedFile = new File(applicationURL+"/"+filePath[filePath.length - 1]);
                long size=uploadedFile.length();
               if(size>=11264)
                {
                   }
                                 try
                                 {
                  fileItem.write(uploadedFile);
                    path = applicationURL.replaceAll
("C:/ProgramFiles/ApacheSoftwareFoundation /Tomcat 6.0/ webapps/apply_smart/", "");
                 path= path + "/"+ filePath[filePath.length - 1];
                  System.out.println("path::::::"+path);                
            }
            catch (java.lang.Exception e)
            {
                out.println(e);
             }
                         }  
      }//else
}
catch(Exception exe)
{
 out.println(exe);
 break;
}       
                }

Please suggest me how to solve the exception and send image to server.

Thanks in advance. -Teja.

Ads

View Answers

January 24, 2012 at 6:24 PM


Hi can anyone help me...am also struggling with same exception..










Tutorials   
Java Spring Hibernate Struts Training Retrieve database from the table dynamically in jsp from oracle using servlet What does core Java include? java What are some way to learn Java quickly? Is it required to learn Java before learning Java Script? Is it necessary to learn java script before learning PHP? Are HTML5 and Java Script boosts Java career? Is Java object oriented? Fingerprint application with Java Uninstall Oracle Virtual Box JSON to HashMap Free Java online Training I want example of Control Statement in Java ANSI Color Codes with Python Create a Program that Calculates Input What is difference between JDK,JRE and JVM? How to see ubuntu version on server? How to get Page Source in Selenium (WebDriver) using Java? The path to the driver executable must be set by the webdriver.gecko.driver system property parse data from a link in java Java Program Qns using BlueJ How to fix HAX Kernel Module Is Not Installed error? Installing Audacity Looking for code Logic to check track changes & Coments in MSWord, MSWordx, MSExcel, MSExcelx is ON/OFF Installing JDK on Mac SAX Parser exception ERROR 601 (42P00): Syntax error. Encountered Thread java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileItemFactory How to install Ubuntu 16.04 LTS? HttpServletRequest cannot be resolved to a type in eclipse - Solved Unhandled event loop exception GC overhead limit exceeded Spring Data jpa with apache phoenix Caused by: java.lang.IllegalArgumentException: Not a host:port pair: PBUF o.a.h.h.z.RecoverableZooKeeper - Possibly transient ZooKeeper, quorum= com.thinkaurelius.titan.diskstorage.hbase.HBaseStoreManager class not found com.thinkaurelius.titan.diskstorage.hbase.HBaseStoreManager not found How to download and install Java 8 on Windows? How to uninstall JDK 7? How to install gtk-doc-tools package in Ubuntu? How to install Oracle JDK 8 on Ubuntu? ejabberd_ctl.beam not found - Solved How to convert date to UTC format in Java? How to install autoconf, automake and libtool in Ubuntu 15.10? How to convert current date to mm dd yyyy format in Java? How to convert current date to dd mm yyyy format in Java? How to stop window closing in "internalFrameClosing" event. How to find list of all index in Neo4j? neo4j-server.properties file location SASLError using PLAIN: not-authorized

Ads

 
Advertisement null

Ads