2012-10-02 78 views
0

我用JavaScript以下形式將文件上載到服務器:爲什麼我無法在服務器端正確獲取formdata?

<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 
[[email protected] 
file = 

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

你正確讀取該文件? – MaVRoSCy

+0

你使用什麼Servlet版本? 2.0還是3.0? – MaVRoSCy

+0

我會建議你閱讀http://stackoverflow.com/questions/3337056/convenient-way-to-parse-incoming-multipart-form-data-parameters-in-a-servlet,更具體地使用http:// commons.apache.org/fileupload/using.html – MaVRoSCy

回答

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,你可以找到有用的

相關問題