代码之家  ›  专栏  ›  技术社区  ›  cuh

在Jersey中使用XML文件进行POST时出现SAXParseException

  •  0
  • cuh  · 技术社区  · 15 年前

    我在休息应用程序中使用JAXB。我想通过Web表单发送一个XML文件。然后Java类将解封 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);
    }
    

    触发 unmarshal 方法有 form 看起来是这样的:

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

    我得到以下ParserException:

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

    这个问题得到了一般性的回答。 here ,但我确信我的文件没有损坏。当我从同一个文件中调用Java类的代码时,不会抛出异常。

    // 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;
    }
    
    3 回复  |  直到 11 年前
        1
  •  1
  •   cuh    14 年前

    @formparam(“file”)inputstream filestream的内容是file=myfile.xml,而不是内容。

        2
  •  0
  •   navr    15 年前

    XML头是否与下面的头类似?

    <?xml version='1.0' encoding='utf-8'?>
    
        3
  •  0
  •   user2937851    11 年前

    确保在验证器中使用的输入流是 重置 验证操作后。 如果不重置它,您可能会得到许多奇怪的异常。

    希望能有所帮助:)