为什么我不能在服务器端正确获取formdata?

时间:2012-10-02 12:13:53

标签: javascript jsp multipartform-data

我有以下形式的javascript将文件上传到服务器:

<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>

服务器端的程序getFontTitle.jsp如下所示:

<%@ 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 ?

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

我已将代码更改为使用FileUpload,它看起来像这样:

<%
  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();

%>

输出结果为:

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

file.length = 35918
file.indexOf(filename=) = -1

1 个答案:

答案 0 :(得分:0)

对于我的表扬我很抱歉,我没有意识到你在哪里使用ajax进行上传(虽然这是一个简单的帖子)。只是它不受支持,但大多数浏览器(How can I upload files asynchronously?)。虽然可以使用更高版本的Chrome和Mozilla,但这可能是jQuery Upload Progress and AJAX file upload

您可以通过提交隐藏的iframe来实现文件上传的跨浏览器功能(此技术是ajax文件上传的事实上的实现)。

还有一些现成的插件,例如http://www.phpletter.com/Demo/AjaxFileUpload-Demo/https://github.com/valums/file-uploader,您可以找到它们