Chanon Deeprasertkul Chanon Deeprasertkul - 4 months ago 34
Java Question

How to let user download zip file using vaadin file downloader

I've followed this topic and it perfectly works. Here's the function to create resource for file downloader

private StreamResource createResource() {
return new StreamResource(new StreamSource() {
@Override
public InputStream getStream() {
String text = "My image";

BufferedImage bi = new BufferedImage(100, 30, BufferedImage.TYPE_3BYTE_BGR);
bi.getGraphics().drawChars(text.toCharArray(), 0, text.length(), 10, 20);

try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bi, "png", bos);
return new ByteArrayInputStream(bos.toByteArray());
} catch (IOException e) {
e.printStackTrace();
return null;
}

}
}, "myImage.png");
}


but i don't know how to make them create a resource of zip file. Do i need to create many resources? I'm sorry if my question is too easy but i don't really get the concept of writing file. Thank you

Answer

Here's the solution that i figured out myself

private StreamResource createZipResource()
{ 
    return new StreamResource(new StreamSource()
    { 
        @Override
        public InputStream getStream()
        {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            try
            {
                ZipOutputStream out = new ZipOutputStream(byteArrayOutputStream);

                for (int i = 0; i < listData.size(); i++)
                {
                    if (listData.get(i).contains(".txt"))
                    { 
                        out.putNextEntry(new ZipEntry(listData.get(i) + ".txt"));
                    }
                    else
                    {
                        out.write(listData.get(i).getBytes());                            
                    } 
                }
                out.close();
                return new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); 
            } 
            catch (IOException e)
            {
                System.out.println("Problem writing ZIP file: " + e);
            }
            return null; 
        }
    },"Filename.zip"); 
}
Comments