REST アプリケーションで jaxb を使用しています。XML ファイルを Web フォーム経由で送信したいと考えています。次に、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
メソッドをトリガーする jsp ファイルには、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.]
.
質問はここで一般的に回答されましたが、ファイルが破損していないことは確かです。同じファイルを使用して java-Class 内からコードを呼び出すと、例外はスローされません。
// 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;
}