简体   繁体   中英

SAXParseException when doing post with a XML file in jersey

I use jaxb in my REST application. I want to send an XML file via a web form. Then the java Class will unmarshal the InputStream .

private void unmarshal(Class<T> docClass, InputStream inputStream)
    throws JAXBException {
    String packageName = docClass.getPackage().getName();
    JAXBContext context = JAXBContext.newInstance(packageName);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    Object marshaledObject = unmarshaller.unmarshal(inputStream);
}

The jsp-File which triggers the unmarshal method has a form which looks like this:

<form action="#" method="POST">
    <label for="id">File</label>
    <input name="file" type="file" />
    <input type="submit" value="Submit" />
</form>

I get the following ParserException :

javax.xml.bind.UnmarshalException - with linked exception: [org.xml.sax.SAXParseException: Content is not allowed in prolog.] .

The question was answered in general here , but i am sure that my file is not corrupt. When i call the code from within a java-Classwith the same file no exception is thrown.

// causes no exception
File file = new File("MyFile.xml");
FileInputStream fis = new FileInputStream(file);
ImportFactory importFactory = ImportFactory.getInstance();
importFactory.setMyFile(fis);

// but when i pass the file with a web form
@POST
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response create(@FormParam("file") InputStream filestream) {
    Response response;

    // is a BufferedInputStream, btw    
    LOG.debug("file is type: " + filestream.getClass().getName());

    try { 
        ImportFactory importFactory = ImportFactory.getInstance();
        importFactory.setMyFile(filestream);

        Viewable viewable = new Viewable("/sucess", null);
        ResponseBuilder responseBuilder = Response.ok(viewable);
        response = responseBuilder.build();

    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        ErrorBean errorBean = new ErrorBean(e);
        Viewable viewable = new Viewable("/error", errorBean);
        ResponseBuilder responseBuilder = Response.ok(viewable);
        response = responseBuilder.build();
    }
    return response;
}

@FormParam(“ file”)InputStream文件流的内容为file = MyFile.xml,而不是其内容。

Make sure that the InputStream you use in the validator is reset after validation operation. Without resetting it you can get many strange exceptions.

I hope it will help :)

XML标头看起来像下面的标头吗?

<?xml version='1.0' encoding='utf-8'?>

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