您的InputStream既不是OLE2流也不是OOXML流

use*_*834 5 java google-app-engine apache-poi

我正在使用Apache Commons在谷歌应用引擎中上传.docx文件,如此链接 文件上传servlet中所述.上传时,我还想使用Apache POI库提取文本.

如果我将其传递给POI API:

 InputStream stream = item.openStream();
Run Code Online (Sandbox Code Playgroud)

我得到以下异常:

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();
}
Run Code Online (Sandbox Code Playgroud)

我正在上传有效的.docx文档.如果我传递FileInputStream对象,POI API工作正常.

FileInputStream fs=new FileInputStream(new File("C:\\docs\\mydoc.docx"));
Run Code Online (Sandbox Code Playgroud)

Pet*_*ego 8

我不知道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();
}
Run Code Online (Sandbox Code Playgroud)