本文介绍了Servlet:从servletinputstream剪切上传头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个从客户端接收xml文件并与之配合使用的servlet.

I'm writing a servlet that receives an xml file from the client and works with it.

我的问题是,在servletinputstream(我从中获得:request.getInputStream())的开头和结尾是一些上传信息:

My problem is, that in the servletinputstream (which i get with: request.getInputStream()) is some upload information at the beginning and at the end:

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

<XML-Content>

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

是否有一个聪明的解决方案,可以将这些行与servletinputstream分开?

Is there a smart solution to cut those lines away from the servletinputstream?

问候

推荐答案

那是multipart/form-data标头(如 RFC2388 ).抓住一个有价值的multipart/form-data解析器,而不是重新发明自己的解析器. Apache Commons FileUpload 是该工作的事实上的标准API.将所需的JAR文件拖放到/WEB-INF/lib中,然后将变得非常简单:

That's a multipart/form-data header (as specified in RFC2388). Grab a fullworthy multipart/form-data parser rather than reinventing your own. Apache Commons FileUpload is the defacto standard API for the job. Drop the required JAR files in /WEB-INF/lib and then it'll be as easy as:

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);
    }

    // ...
}

再一次,不要重塑自己的.您真的不想进行维护.

Once again, don't reinvent your own. You really don't want to have a maintenance aftermath.

这篇关于Servlet:从servletinputstream剪切上传头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 09:23