title: Why can't I get the formdata correctly on the server side?
body: <p>I have the following form with javascript that uploads a file to a server :</p>
  
  <pre><code>&lt;h1&gt;Upload Font&lt;/h1&gt;                                                       
  &lt;form id="add" name="add" action="/font/add" method="POST" enctype="multipart/form-data"&gt;
    &lt;div class="dialog"&gt;
      &lt;table&gt;
        &lt;tbody&gt;
          &lt;tr class="prop"&gt;
            &lt;td valign="top" class="name required"&gt;
              &lt;label for="description"&gt;Font Description:&lt;/label&gt;
            &lt;/td&gt;
            &lt;td valign="top"&gt;
              &lt;input type="text" name="font.description" size="44" value="" id="name"/&gt;      
            &lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr class="prop"&gt;
            &lt;td valign="top" class="name required"&gt;
              &lt;label for="description"&gt;Font File:&lt;/label&gt;
            &lt;/td&gt;
            &lt;td valign="top"&gt;
              &lt;input type="file" name="file" size="62" value="" id="fname" onchange="fileUpload('/pages/font/getFontTitle.jsp',value,this.files[0])"/&gt;
            &lt;/td&gt;
          &lt;/tr&gt; 
          &lt;tr class="prop"&gt;
            &lt;td&gt;
              &lt;span class="button"&gt;&lt;div align="right" id="wwctrl_add_0"&gt;&lt;input type="submit" id="add_0" value="Submit"/&gt;&lt;/div&gt;&lt;/span&gt;
            &lt;/td&gt;
          &lt;/tr&gt; 
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt; 
  &lt;/form&gt;
  
  &lt;script type="text/javascript"&gt;
  
    function fileUpload(url,fileName,fileData)
    {
      try
      {    
        var fileSize=fileData.size;
  alert('fileSize : '+fileSize); 
        if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();                   // code for IE7+, Firefox, Chrome, Opera, Safari
        else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");                       // code for IE6, IE5 
        xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 &amp;&amp; xmlhttp.status==200) document.getElementById('name').value=xmlhttp.responseText; }
        xmlhttp.open("POST",url,true);
        var formdata=new FormData();
        formdata.append('fileName',fileName);
        formdata.append('file',fileData);
        xmlhttp.send(formdata);
      }
      catch(e) { alert(e.message); }
    }
  &lt;/script&gt;
  </code></pre>
  
  <p>My program getFontTitle.jsp on the server side look like this :</p>
  
  <pre><code>&lt;%@ page import="java.io.*" %&gt;
  &lt;%@ page import="java.awt.*" %&gt;
  
  &lt;%
    String contentType=request.getContentType(),Location="0.",                   // To get the content type information from JSP Request Header
               fontAttributes="",fontTitle="";
  System.out.println("contentType = "+contentType);
    if ((contentType!=null) &amp;&amp; (contentType.indexOf("multipart/form-data")&gt;=0))  // Here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0
    {
  Location+="1.";
      try
      {
        DataInputStream in=new DataInputStream(request.getInputStream());
        int formDataLength=request.getContentLength();                           // We are taking the length of Content type data
        byte dataBytes[]=new byte[formDataLength];
        int byteRead=0;
        int totalBytesRead=0;
  
        while (totalBytesRead&lt;formDataLength)                                    // This loop converting the uploaded file into byte code
        {
          byteRead=in.read(dataBytes,totalBytesRead,formDataLength);
          totalBytesRead+=byteRead;
        }
  System.out.println("dataBytes : "+dataBytes.length+"\n"+dataBytes.toString());
  
        String file=new String(dataBytes);
  System.out.println("file = \n"+file);
  System.out.println("file.length = "+file.length());
  
  System.out.println("file.indexOf(filename=) = "+file.indexOf("filename=\""));
  String saveFile=file.substring(file.indexOf("filename=\"")+10);          // For saving the file name
        Location+="2.";
        saveFile=saveFile.substring(0,saveFile.indexOf("\n"));
  System.out.println("saveFile = "+saveFile);
        Location+="3.";
        saveFile=saveFile.substring(saveFile.lastIndexOf("\\")+1,saveFile.indexOf("\""));
        Location+="4.";
        int lastIndex=contentType.lastIndexOf("=");
        Location+="5.";
        String boundary=contentType.substring(lastIndex+1,contentType.length());
  System.out.println(" boundary = "+boundary);
        int pos;
        Location+="6.";
        pos=file.indexOf("filename=\"");                                         // Extracting the index of file 
        Location+="7.";
        pos=file.indexOf("\n",pos)+1;
        pos=file.indexOf("\n",pos)+1;
        pos=file.indexOf("\n",pos)+1;
        Location+="8.";
        int boundaryLocation=file.indexOf(boundary,pos)-4;
        System.out.println(" boundaryLocation = "+boundaryLocation+"  filename = "+file.indexOf("filename=\""));
        int startPos=((file.substring(0,pos)).getBytes()).length;
        int endPos=((file.substring(0,boundaryLocation)).getBytes()).length;
        System.out.println(" startPos = "+startPos+" , endPos = "+endPos);
  
        Location+="9.";
        File f=new File(saveFile);
        FileOutputStream fileOut=new FileOutputStream(f);
  //      fileOut.write(dataBytes,startPos,(endPos-startPos));
        fileOut.write(dataBytes);
        fileOut.flush();
        fileOut.close();
  
  Location+="a.";
  //      System.out.println("================================\nstartPos = "+startPos+" , endPos = "+endPos+"\nf = "+f+"\nf.getAbsolutePath() = "+f.getAbsolutePath()+"\n\n=== contentType ===\n\n"+contentType+"\n\n=== file ===\n\n"+file+"\n================================");
  //    out.println(f+"&lt;Br&gt;"+file);
  Location+="b.";
        Font createdFont=Font.createFont(Font.TRUETYPE_FONT,new FileInputStream(f));
  Location+="c.";
  
  //      System.out.println(createdFont);
  Location+="d.";
        fontAttributes=createdFont.getAttributes().toString();                   // map of {family="A.C.M.E. Explosive Bold", weight=1.0*, width=1.0*, posture=0.0*, size=1.0, transform=null*, superscript=0*, tracking=0.0*[btx=null, ctx=null]}
        System.out.println(fontAttributes);
        fontTitle=fontAttributes.substring(fontAttributes.indexOf("\"")+1,fontAttributes.lastIndexOf("\""));
        out.println(fontTitle);
  Location+="e.";
  
  //      out.println("Done : "+saveFile);
  
      }
      catch (Exception e) { e.printStackTrace(); }
  Location+="f.";
    }
    else if (contentType==null) out.println("Not a valid file");
    out.println(" [ "+Location+" ]");
  
    out.flush();
  
  %&gt;
  
  The output look like this : [ 0.1.2.f. ]
  There is error on line : saveFile=saveFile.substring(0,saveFile.indexOf("\n"));
  There is no index of saveFile.indexOf("\n")
  What did I do wrong ? Maybe it's not getting the data in the correct format ?
  </code></pre>
  
  <p>==========================================</p>
  
  <p>I've changed the code to use FileUpload, it looks like this :</p>
  
  <pre><code>&lt;%
    String contentType=request.getContentType(),Location="0.",                   // To get the content type information from JSP Request Header
               fontAttributes="",fontTitle="";
  out.println("Done");
  System.out.println("contentType = "+contentType);
  
    boolean isMultipart=ServletFileUpload.isMultipartContent(request);           // Check that we have a file upload request
    System.out.println("isMultipart = "+isMultipart);
  
    FileItemFactory factory=new DiskFileItemFactory();                           // Create a factory for disk-based file items
    ServletFileUpload upload=new ServletFileUpload(factory);                     // Create a new file upload handler
    List /* FileItem */ items=upload.parseRequest(request);                      // Parse the request
  
    Iterator iter=items.iterator();                                              // Process the uploaded items
    while (iter.hasNext())
    {
      FileItem item=(FileItem) iter.next();
      if (item.isFormField())                                                    // Process a regular form field
      {
          String name=item.getFieldName();
        String value=item.getString();
        System.out.println("name = "+name+"  value = "+value);
      }
      else
      {
        String fieldName = item.getFieldName();
        String fileName = item.getName();
        contentType = item.getContentType();
        boolean isInMemory = item.isInMemory();
        long sizeInBytes = item.getSize();
        System.out.println("isInMemory = "+isInMemory+"  sizeInBytes = "+sizeInBytes);
  
      }
    }
  
    if ((contentType!=null) &amp;&amp; (contentType.indexOf("multipart/form-data")&gt;=0))  // Here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0
    {
  Location+="1.";
      try
      {
        DataInputStream in=new DataInputStream(request.getInputStream());
        int formDataLength=request.getContentLength();                           // We are taking the length of Content type data
        byte dataBytes[]=new byte[formDataLength];
        int byteRead=0;
        int totalBytesRead=0;
  
        while (totalBytesRead&lt;formDataLength)                                    // This loop converting the uploaded file into byte code
        {
          byteRead=in.read(dataBytes,totalBytesRead,formDataLength);
          totalBytesRead+=byteRead;
        }
  System.out.println("dataBytes : "+dataBytes.length+"\n"+dataBytes.toString());
  </code></pre>
  
  <p>....</p>
  
  <pre><code>    }
      catch (Exception e) { e.printStackTrace(); }
  Location+="f.";
    }
    else if (contentType==null) out.println("Not a valid file");
    out.println(" [ "+Location+" ]");
  
    out.flush();
  
  %&gt;
  </code></pre>
  
  <p>The output is :</p>
  
  <pre><code>contentType = multipart/form-data; boundary=---------------------------184228830106
  isMultipart = true
  dataBytes : 35918
  [B@1c8365b
  file =
  
  file.length = 35918
  file.indexOf(filename=) = -1
  </code></pre>