下载文件vaadin

时间:2013-07-01 20:36:14

标签: java file web-applications bytearray vaadin

我创建了一个将其数据源设置为BeanItemContainer的taable。每个bean都有一个名称(String)和一个byte [],它保存一个转换为byte []的文件。我为每一行添加了一个按钮,假设首先将其转换为pdf,即可下载该文件。我在实现下载部分时遇到问题,这是相关的代码:

public Object generateCell(Table source, Object itemId,
                Object columnId) {
            // TODO Auto-generated method stub
            final Beans p = (Beans) itemId;

            Button l = new Button("Link to pdf");
            l.addClickListener(new Button.ClickListener() {

                @Override
                public void buttonClick(ClickEvent event) {
                    // TODO Auto-generated method stub

                    try {
                        FileOutputStream out = new FileOutputStream(p.getName() + ".pdf");
                        out.write(p.getFile());
                        out.close();

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            });
            l.setStyleName(Reindeer.BUTTON_LINK);

            return l;
        }


    });

因此getFile从bean获取字节数组

2 个答案:

答案 0 :(得分:8)

如果您使用的是Vaadin 7,则可以使用此处所述的FileDownloader扩展程序:https://vaadin.com/forum#!/thread/2864064

您需要扩展按钮,而不是使用clicklistener:

Button l = new Button("Link to pdf");
StreamResource sr = getPDFStream();
FileDownloader fileDownloader = new FileDownloader(sr);
fileDownloader.extend(l);

获取StreamResource:

private StreamResource getPDFStream() {
        StreamResource.StreamSource source = new StreamResource.StreamSource() {

            public InputStream getStream() {
                // return your file/bytearray as an InputStream
                  return input;

            }
        };
      StreamResource resource = new StreamResource ( source, getFileName());
        return resource;
}

答案 1 :(得分:3)

生成的列创建在Book of Vaadin中有详细描述,对代码的一个更正是检查columnId或propertyId以确保在右列中创建一个按钮 - 目前看来你返回任何列的按钮。 / p>

这样的事情:



    public Object generateCell(CustomTable source, Object itemId, Object columnId)
    {
        if ("Link".equals(columnId))
        {
            // ...all other button init code is omitted...
            return new Button("Download");
        }
        return null; 
    }

下载文件:



    // Get instance of the Application bound to this thread
    final YourApplication app = getCurrentApplication();
    // Generate file basing on your algorithm
    final File pdfFile = generateFile(bytes);
    // Create a resource
    final FileResource res = new FileResource(pdfFile, app);
    // Open a resource, you can also specify target explicitly - 
    // i.e. _blank, _top, etc... Below code will just try to open 
    // in same window which will just force browser to show download
    // dialog to user
    app.getMainWindow().open(res);

有关如何处理资源的更多信息,请参阅Book of Vaadin