Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8632739
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T09:23:36+00:00 2026-06-12T09:23:36+00:00

I have the following form with javascript that uploads a file to a server

  • 0

I have the following form with javascript that uploads a file to a server :

<h1>Upload Font</h1>                                                       
<form id="add" name="add" action="/font/add" method="POST" enctype="multipart/form-data">
  <div class="dialog">
    <table>
      <tbody>
        <tr class="prop">
          <td valign="top" class="name required">
            <label for="description">Font Description:</label>
          </td>
          <td valign="top">
            <input type="text" name="font.description" size="44" value="" id="name"/>      
          </td>
        </tr>
        <tr class="prop">
          <td valign="top" class="name required">
            <label for="description">Font File:</label>
          </td>
          <td valign="top">
            <input type="file" name="file" size="62" value="" id="fname" onchange="fileUpload('/pages/font/getFontTitle.jsp',value,this.files[0])"/>
          </td>
        </tr> 
        <tr class="prop">
          <td>
            <span class="button"><div align="right" id="wwctrl_add_0"><input type="submit" id="add_0" value="Submit"/></div></span>
          </td>
        </tr> 
      </tbody>
    </table>
  </div> 
</form>

<script type="text/javascript">

  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 && 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); }
  }
</script>

My program getFontTitle.jsp on the server side look like this :

<%@ page import="java.io.*" %>
<%@ page import="java.awt.*" %>

<%
  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) && (contentType.indexOf("multipart/form-data")>=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<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+"<Br>"+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();

%>

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 ?

==========================================

I’ve changed the code to use FileUpload, it looks like this :

<%
  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) && (contentType.indexOf("multipart/form-data")>=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<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());

….

    }
    catch (Exception e) { e.printStackTrace(); }
Location+="f.";
  }
  else if (contentType==null) out.println("Not a valid file");
  out.println(" [ "+Location+" ]");

  out.flush();

%>

The output is :

contentType = multipart/form-data; boundary=---------------------------184228830106
isMultipart = true
dataBytes : 35918
[B@1c8365b
file =

file.length = 35918
file.indexOf(filename=) = -1
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T09:23:36+00:00Added an answer on June 12, 2026 at 9:23 am

    I am so sorry for my commends, i did not realize that you where doing the uploading using ajax (i though it was a simple post) . Simply it is not supported but most browsers ( How can I upload files asynchronously? ). Using later versions of Chrome and Mozilla this might be possible though ( jQuery Upload Progress and AJAX file upload )

    You can achieve a cross browser functionality for files uploading by submitting a hidden iframe (this technique is the de facto implementation of ajax file uploading).

    There are also some ready made plugins such as http://www.phpletter.com/Demo/AjaxFileUpload-Demo/ and https://github.com/valums/file-uploader that you can find usefull

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following form: <form id=vintro-upload-form action={url}?nexturl={nextUrl} method=post enctype=multipart/form-data > <input name=file type=file/>
I have the following form <form name=myForm id=myForm method=post enctype=multipart/form-data action=script.php> and this jQuery
I have the following form that has 2 selects: <form id=form class=form_visitar method=post action=ajax/selects.php>
I have a form that allows for multiple file uploads. <input name=uploadedfile[] type=file multiple=true/>
for the following form <form action ='search.php' method = 'post'> <select name=filter> <option id=A
i have the following javascript to post a form through ajax without refreshing the
i have the following function in jQuery and javascript that creates a form element:
Let's say I have the following scenario: <form action=/something.php method=GET>Click me</div> <script type=text/javascript><!-- $('form').submit(function(e)
I have the following form in a website of mine. <form action= method=GET> <input
I have the following form in a Struts2 JSP that contains some radio buttons.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.