2010-08-10 52 views
2

我在寫一個servlet,它從客戶端接收xml文件並使用它。Servlet:從servletinputstream切割上傳頭

我的問題是,在servletinputstream(我用得到:request.getInputStream())是在開始和結束時的一些載信息:

-----------------------------186292285129788 
Content-Disposition: form-data; name="myFile"; filename="TASKDATA - Kopie.XML" 
Content-Type: text/xml 

<XML-Content> 

-----------------------------186292285129788-- 

是否有一個聰明的解決方案,以削減遠離servletinputstream的那些線?

問候

回答

1

這是一個multipart/form-data報頭(如在RFC2388指定)。抓取一個完整的multipart/form-data解析器,而不是重新創建自己的。 Apache Commons FileUpload是該工作的事實標準API。刪除所需的JAR文件/WEB-INF/lib,然後它會是那麼容易,因爲:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    try { 
     List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); 
     for (FileItem item : items) { 
      if (item.isFormField()) { 
       // Process regular form field (input type="text|radio|checkbox|etc", select, etc). 
       String fieldname = item.getFieldName(); 
       String fieldvalue = item.getString(); 
       // ... (do your job here) 
      } else { 
       // Process form file field (input type="file"). 
       String fieldname = item.getFieldName(); 
       String filename = FilenameUtils.getName(item.getName()); 
       InputStream filecontent = item.getInputStream(); 
       // ... (do your job here) 
      } 
     } 
    } catch (FileUploadException e) { 
     throw new ServletException("Cannot parse multipart request.", e); 
    } 

    // ... 
} 

再次,不要重新發明自己。你真的不想維護後果。

0

如果你的問題是,你想讀的流媒體文件(性能),檢查此鏈接 http://commons.apache.org/proper/commons-fileupload/streaming.html

(從鏈接):

// Check that we have a file upload request 
boolean isMultipart = ServletFileUpload.isMultipartContent(request); 

// Create a new file upload handler 
ServletFileUpload upload = new ServletFileUpload(); 

// Parse the request 
FileItemIterator iter = upload.getItemIterator(request); 
while (iter.hasNext()) { 
    FileItemStream item = iter.next(); 
    String name = item.getFieldName(); 
    InputStream stream = item.getInputStream(); 
    if (item.isFormField()) { 
     System.out.println("Form field " + name + " with value " 
      + Streams.asString(stream) + " detected."); 
    } else { 
     System.out.println("File field " + name + " with file name " 
      + item.getName() + " detected."); 
     // Process the input stream 
     ... 
    } 
}