简体   繁体   中英

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.

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM