我正在使用 Apache Commons 在 Google 应用程序引擎中上传 .docx 文件,如本链接中所述文件上传 Servlet https://developers.google.com/appengine/kb/java?csw=1#fileforms。上传时,我还想使用 Apache POI 库提取文本。
如果我将其传递给 POI API:
InputStream stream = item.openStream();
我得到以下异常:
java.lang.IllegalArgumentException: Your InputStream was neither an OLE2 stream, nor an OOXML stream
public static String docx2text(InputStream is) throws Exception {
return ExtractorFactory.createExtractor(is).getText();
}
我正在上传有效的 .docx 文档。如果我传递 FileInputStream 对象,POI API 工作正常。
FileInputStream fs=new FileInputStream(new File("C:\\docs\\mydoc.docx"));
我不知道 POI 内部实现,但我的猜测是他们需要一个可查找的流。 Servlet(以及一般的网络)返回的流是不可查找的。
尝试阅读全部内容,然后将其包含在内ByteArrayInputStream
:
byte[] bytes = getBytes(item.openStream());
InputStream stream = new ByteArrayInputStream(bytes);
public static byte[] getBytes(InputStream is) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int len;
byte[] data = new byte[100000];
while ((len = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, len);
}
buffer.flush();
return buffer.toByteArray();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)