我正在编写一个servlet,它从客户端接收xml文件并使用它。
我的问题是,在servletinputstream(我得到的:request.getInputStream())中有一些开头和结尾的上传信息:
-----------------------------186292285129788
Content-Disposition: form-data; name="myFile"; filename="TASKDATA - Kopie.XML"
Content-Type: text/xml
<XML-Content>
-----------------------------186292285129788--
是否有一种智能解决方案可以将这些线从servletinputstream中删除?
问候
答案 0 :(得分:1)
这是multipart/form-data
标头(在RFC2388中指定)。获取一个完整的multipart/form-data
解析器,而不是重新发明自己的解析器。 Apache Commons FileUpload是该作业的事实标准API。删除/WEB-INF/lib
中所需的JAR文件,然后就像以下一样简单:
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);
}
// ...
}
再一次,不要重塑自己。你真的不希望得到维护后果。
答案 1 :(得分: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
...
}
}