-3

我试图在我的响应正文中一次发送多个文件。我的问题是我无法将多个数组列表连接成一个,然后我可以将其重新分成多个文件。

这是我的代码(不起作用):

       List<PDDocument> documents =  splitter.split(PDDocument.load(documentData));
            ArrayList<byte[]> newDocuments = new ArrayList<>();
            for (PDDocument doc : documents)
            {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                doc.save(os);
                newDocuments.add(os.toByteArray());
                os.close();


            }
            t.sendResponseHeaders(200,newDocuments.toArray().length);;
            OutputStream responseBody = t.getResponseBody();
            responseBody.write(newDocuments.toArray());
            responseBody.close();

所以我的问题是:

如何使用 java 11 http 服务器将多个文件发送回单个 http 响应?

谢谢 !

更新 :

在 Joni 的帮助下修复我的代码后,我面临另一个问题:生成的 Zip 已损坏:

这是代码:

   Splitter splitter = new Splitter();
            List<PDDocument> documents =  splitter.split(PDDocument.load(documentData));


            t.sendResponseHeaders(200, 0);
            t.getResponseHeaders().set("Content-Type", "application/zip");

            OutputStream responseBody = t.getResponseBody();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(baos);


            int counter = 1;
            for (PDDocument doc : documents)
            {
                ZipEntry zipEntry = new ZipEntry("document" + counter);
                zos.putNextEntry(zipEntry);
                ByteArrayOutputStream docOs = new ByteArrayOutputStream();
                doc.save(docOs);
                docOs.close();
                zos.write(docOs.toByteArray());
                zos.closeEntry();
                zos.finish();
                zos.flush();

                counter++;
            }
            zos.close();
            baos.close();


            responseBody.write(baos.toByteArray());
            responseBody.flush();


            responseBody.close();
4

1 回答 1

2

You cannot send multiple files in a HTTP response.

What you can do is put multiple files in one "compressed archive" file such as a ZIP file, and send that instead. For example:

        t.getResponseHeaders().set("Content-Type", "application/zip");
        t.sendResponseHeaders(200, 0);
        OutputStream responseBody = t.getResponseBody();
        ZipOutputStream zos = new ZipOutputStream(responseBody);
        int counter = 1;
        for (PDDocument doc : documents)
        {
            ZipEntry zipEntry = new ZipEntry("document"+counter);
            zos.putNextEntry(zipEntry);
            doc.save(zos);
            zos.closeEntry();
            counter++;
        }
        zos.close();
于 2020-08-24T12:23:31.207 回答