Download multiple files

Hi. I want to download two files created on-the-fly by single button click. While I found how to do it only for single file. How to add one more StreamResource to this?

Anchor export = new Anchor(new StreamResource("export.xlsx", …), "");
export.getElement().setAttribute("download", true);
export.add(new Button("Export"));

Hi Mikhail, Did you ever find out how to accomplish multiple file download?

If dynamically creating a zip file that contains several files (also dynamically created from Strings) without having actual files on the filesystem is ok for you instead, you could do sth like:

public byte[] zipFiles(List<Pair<String, String>> files) throws IOException {
    try (final var baos = new ByteArrayOutputStream();
         final var zos = new ZipOutputStream(baos)) {

        for (Pair<String, String> file : files) {
            String filename = file.getFirst();
            byte[] content = file.getSecond().getBytes();
            ZipEntry entry = new ZipEntry(filename);
            entry.setSize(content.length);
            zos.putNextEntry(entry);
            zos.write(content);
            zos.closeEntry();
        }
        zos.finish();
        zos.flush();
        zos.close();
        return baos.toByteArray();
    }
}

and then for your link

StreamResource streamResource =
        new StreamResource(
                "zipFileName.zip",
                () -> new ByteArrayInputStream(**zipFiles(files)**));
myAnchor.setHref(streamResource);

That’s a great solution, thanks for that!