Wicket: загрузка файлов после onSubmit

Итак, у меня есть DataView с тремя столбцами, один из которых является столбцом с флажком, который позволяет пользователям проверять, какие файлы они хотели бы загрузить.

Для простоты (я думаю); Я решил сжать файлы в один zip-файл и предоставить его после того, как он будет сгенерирован.

Вот что у меня есть до сих пор:

Код::


    Button downloadLogButton = new Button("downloadlogbutton") {
        private static final long serialVersionUID = 1L;
        @Override
        public void onSubmit() {
            // Some utility class I made that zips files
            LogUtility util = new LogUtility();
            util.zipLogFiles("sample", logs);
        }
    };

    Form logsForm = new Form("logsform") {

    };

    logsForm.add(downloadLogButton);

    CheckGroup<File> checkGroup = new CheckGroup<File>("logscheckgroup", new ArrayList<File>());
    WebMarkupContainer logsViewContainer = new WebMarkupContainer("datatable");
    DataView<File> logsView = new DataView<File>("logrows", new ListDataProvider<File>(logs)) {

        private static final long serialVersionUID = 1L;

        public void populateItem(final Item<File> item) {
            final File file = (File) item.getModelObject();
            item.add(new Check<File>("logdownloadcheck", item.getModel()));
            item.add(new Label("logname", file.getName()));
            SimpleDateFormat sdf = new SimpleDateFormat( "E, dd MMM yyyy  hh:mm a");
            item.add(new Label("logdatemodified", sdf.format(file .lastModified())));
        }
    };

    logsViewContainer.add(logsView);
    checkGroup.add(logsViewContainer);
    logsForm.add(checkGroup);
    add(logsForm);

Как передать zip-файл после его создания для загрузки? Каковы мои варианты? Мне бы не хотелось перенаправлять их на страницу подтверждения или страницу Your download is ready.

ОБНОВЛЕНИЕ

Основываясь на ответе Хави Лопеса, я добавил следующий код в свою функцию Button onSubmit.

org.apache.wicket.util.file.File log = new org.apache.wicket.util.file.File("/home/keeboi/Downloads/sample.zip");

IResourceStream resourceStream = new FileResourceStream(log);
IRequestHandler target = new ResourceStreamRequestHandler(resourceStream);

getRequestCycle().scheduleRequestHandlerAfterCurrent(target);

И я получаю HTTP Error 404: Not Found.


person Kevin D.    schedule 11.01.2013    source источник


Ответы (1)


Вы можете сделать так же, как DownloadLink, и создать FileResourceStream из заархивированного файла. Затем просто измените цель текущего цикла запроса:

Button downloadLogButton = new Button("downloadlogbutton") {
    private static final long serialVersionUID = 1L;
    @Override
    public void onSubmit() {
        // Some utility class I made that zips files
        LogUtility util = new LogUtility();
        util.zipLogFiles("sample", logs);
        IResourceStream resourceStream = new FileResourceStream(
            new org.apache.wicket.util.file.File(someFile)); // Use whatever file you need here
        IRequestTarget t = new ResourceStreamRequestTarget(stream){
            @Override
            public String getFileName() {
                return "filename.zip";
            }
        }
        getRequestCycle().setRequestTarget(t);
    }
};

Если вы хотите удалить файл после загрузки, вы можете переопределить IRequestTarget#respond(RequestCycle) следующим образом:

@Override
public void respond(RequestCycle requestCycle) {
    super.respond(requestCycle);
    // Delete the file
    ((FileResourceStream)getResourceStream()).getFile().delete();
}

Также может быть полезен следующий связанный вопрос: Как использовать DownloadLink Wicket с файлом, созданным на лету?.

person Xavi López    schedule 11.01.2013
comment
Поскольку я использую Wicket 1.5, я сделал это так: org.apache.wicket.util.file.File log = new org.apache.wicket.util.file.File("/home/keeboi/Downloads/sample.zip"); IResourceStream resourceStream = new FileResourceStream(log); IRequestHandler target = new ResourceStreamRequestHandler(resourceStream); getRequestCycle().scheduleRequestHandlerAfterCurrent(target); Но я получаю HTTP Error 404: Not found - person Kevin D.; 14.01.2013
comment
Хорошо, это была ошибка в моем классе полезности. Спасибо! - person Kevin D.; 14.01.2013