why this exception FileItemStream$ItemSkippedException?

风格不统一 提交于 2019-12-04 07:52:55

Answer a bit late but I had the same problem.

Why you get that exception: The JavaDocs of ItemSkippedException explain a little bit:

This exception is thrown, if an attempt is made to read data from the InputStream, which has been returned by FileItemStream.openStream(), after Iterator.hasNext() has been invoked on the iterator, which created the FileItemStream.

You are using the InputStream stream outside the while loop which causes the problem because another iteration is called which closes (skips) the file InputStream you try to read from.

Solution: Use the InputStream inside the while loop. If you need all form-fields before processing the file, ensure you set it in the right order on client side. First all fields, last the file. For example using the JavaScript FormData:

var fd = new window.FormData();

fd.append("param1", param1);
fd.append("param2", param2);

// file must be last parameter to append
fd.append("file", file);

And on server side:

FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
    FileItemStream item = iter.next();
    InputStream stream = item.openStream();

    // the order of items is given by client, first form-fields, last file stream
    if (item.isFormField()) {
        String name = item.getFieldName();
        String value = Streams.asString(stream);
        // here we get the param1 and param2
    } else {
        String filename = item.getName();
        String mimetype = item.getContentType();

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        int nRead;
        while ((nRead = stream.read(buffer, 0, buffer.length)) != -1) {
            System.out.println("lenth111" +nRead);
            output.write(buffer, 0, nRead);
        }
        System.out.println("lenth" +nRead);
        output.flush(); 
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!