views:

29

answers:

2

Hello,

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

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

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

greetings

A: 

There are many classes etc that take care of this situation. Most modern app frameworks also hide this sort of necessary but mundane code from the developer. However, if you want to do it, here is a good place to look (first google result, but old):

http://cit3.cdn.swin.edu.au/utilities/upload/File_Upload_Using_Java.html

Java Drinker
+1  A: 

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.

BalusC