文件内容显示在浏览器窗口中,而不是作为下载发送

时间:2016-07-08 17:09:03

标签: vaadin

我正在尝试将一些内容作为txt文件发送为下载,但该文件在浏览器中打开而不是作为下载发送。这是我的代码: -

    StreamResource res = new StreamResource(new StreamSource() {

        @Override
        public InputStream getStream() {
            StringBuffer buf = new StringBuffer();
            for (String record : records)
                buf.append(record);
            ByteArrayInputStream is = new ByteArrayInputStream(new String(buf).getBytes());
            return is;
        }
    }, filenameReport, app);
    res.setMIMEType("text/plain");
    res.getStream().setParameter("Content-Disposition", "attachment; filename=" + filenameReport);
    btnGet.getWindow().open(res);

1 个答案:

答案 0 :(得分:1)

打开窗口会打开一个窗口(这就是为什么这样命名的原因)

使用here

所述的文件FileDownloader

基本用法是:

public class LettingUserDownladFile extends UI {

    @Override
    protected void init(VaadinRequest request) {
        Button downloadButton = new Button("Download image");

        StreamResource myResource = createResource();
        FileDownloader fileDownloader = new FileDownloader(myResource);
        fileDownloader.extend(downloadButton);

        setContent(downloadButton);
    }

    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");
    }

}