Colin747
Colin747

Reputation: 5013

Uploading XML using a Java Servlet

I used the following code to upload a file, at the moment it uploads a file without <..> however I wish to upload an XML file. How do I upload the file?

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if(isMultipart){
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try{
            List<FileItem> fields = upload.parseRequest(request);
            Iterator<FileItem> it = fields.iterator();
            while (it.hasNext()) {
                FileItem fileItem = it.next();

                out.println(fileItem.getString());
          }
        }catch (FileUploadException e) {
            e.printStackTrace();
        }       
    }
}

EDIT: For example if I upload a file containing Screens><Screen only Screens> is outputted.

Upvotes: 0

Views: 1854

Answers (2)

fvu
fvu

Reputation: 32953

I don't immediately see an issue with your code, but because of

response.setContentType("text/html;charset=UTF-8");

you are telling the browser on the receiving end that it's getting html, and thus it will try to interpret the data it receives as HTML. Try sending the data out using the proper content type:

response.setContentType("application/xml;charset=UTF-8");

What puzzles me is the tag your remark : Screens><Screen That's not valid xml. If correcting the content type doesn't work, you can add a real test (one that resembles a minimal sample of your data) to your question, together with the effective output.

Upvotes: 1

Syed Muhammad Humayun
Syed Muhammad Humayun

Reputation: 459

If you are viewing the output on a browser, then try viewing the source code:

For IE - right click on the page and select "View Source"

For FF & Chrome - right click on the page and select "View Page Source"

Upvotes: 0

Related Questions