使用AjaxLazyLoadPanel下载文件

时间:2013-09-09 09:06:10

标签: java wicket

以下代码的想法是在加载延迟加载的面板时在浏览器中显示下载对话框。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.wicket.Component;
import org.apache.wicket.extensions.ajax.markup.html.AjaxLazyLoadPanel;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.request.handler.resource.ResourceStreamRequestHandler;
import org.apache.wicket.request.resource.ContentDisposition;
import org.apache.wicket.util.resource.AbstractResourceStreamWriter;

public class LazyLoadedPage extends WebPage {

    public LazyLoadedPage() {
        add(new Label("text", "waiting..."));
        add(new AjaxLazyLoadPanel("lazy") {

            @Override
            public Component getLazyLoadComponent(final String id) {
                try {
                    Thread.sleep(2000);
                } catch (final InterruptedException e) {
                    throw new RuntimeException(e);
                }
                final ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler(new Resource(),
                        "test2.txt");
//                handler.setContentDisposition(ContentDisposition.ATTACHMENT);
                getRequestCycle().scheduleRequestHandlerAfterCurrent(handler);
                return new EmptyPanel(id);
            }
        });
    }

    class Resource extends AbstractResourceStreamWriter {

        @Override
        public void write(final OutputStream output) throws IOException {
            final File tempFile = File.createTempFile("test", "txt");
            final FileOutputStream fos = new FileOutputStream(tempFile);
            fos.write("text".getBytes());
            fos.close();

            final FileInputStream fis = new FileInputStream(tempFile);
            final byte[] buff = new byte[10];
            final int cnt = fis.read(buff);
            output.write(buff, 0, cnt);
        }

    }

}

但是当我尝试它时,我在Wicket Ajax调试窗口中收到此错误:

ERROR: Wicket.Ajax.Call.failure: Error while parsing response: Error: Invalid XML: text

如何修复我的代码(可能使用其他方法)?

1 个答案:

答案 0 :(得分:0)

最后我使用了Apache wiki的AJAXDownload