在primefaces fileDownload完成后调用动作(删除临时文件)

时间:2016-01-12 10:27:40

标签: jsf primefaces

在我的JSF 2.2,Primefaces 5.2应用程序中,我的业务逻辑要求---当用户下载文件时 - 我将几个文件打包成一个临时zip文件,然后流式传输给用户。现在,在成功下载后,我无法删除(清理)临时文件。

我尝试按如下方式调用文件删除:

视图:

<p:commandButton value="#{msg['common.actions.download']}"
    ajax="false" onclick="PrimeFaces.monitorDownload(start, stop);"
    icon="fa fa-download">
    <p:fileDownload value="#{kundeController.getFile(file)}" />
</p:commandButton>

<p:remoteCommand name="stop" oncomplete="PF('statusDialog').hide()"
                    actionListener="#{customerController.downloadFinished()}">
</p:remoteCommand>

来自我的视图范围bean(CustomerController)的相关方法:

public StreamedContent getFile(FileDto fileToLoad) {
    selectedFile = fileToLoad;
    try {
        tmpFilePath = fileService.getFilePath(fileToLoad);

        fis = new FileInputStream(tmpFilePath.toFile());
        sreamedContent = new DefaultStreamedContent(fis, "", fileToLoad.getOriginalFilename);

        return sreamedContent;

    } catch (IOException e) {
        showMessage(FacesMessage.SEVERITY_ERROR, "download.generic.error", "", null);
        logger.error("Problem to load {}", fileToLoad.getPfad(), e);
        throw new AbortProcessingException();
    }

}

public void downloadFinished() {
    logger.info("Download finished");
    try {
        logger.info("attempting to delete {}", tmpFilePath.toString());
        sreamedContent.getStream().close();
        Files.deleteIfExists(tmpFilePath);
    } catch (IOException e) {
        logger.error("error while deleting temp-file", e);
    }
    logger.info("deleted temp-file");
}

使用方法fileService.getFilePath(FileDto fileToLoad)在方法java.nio.file.Files.createTempFile(String filename)中创建临时文件。

似乎在下载整个文件之前调用了远程命令“stop”:一旦关闭流,下载就会中断。

11:13:28.690 [http-nio-8080-exec-6] INFO  myApp.controller.CustomerController - attempting to delete C:\Users\myname\AppData\Local\Temp\tmp_420062840599424196.zip
Jan 12, 2016 11:13:28 AM com.sun.faces.lifecycle.InvokeApplicationPhase execute
WARNING: java.io.IOException: Stream Closed
javax.faces.FacesException: java.io.IOException: Stream Closed
    at org.primefaces.component.filedownload.FileDownloadActionListener.processAction(FileDownloadActionListener.java:90)

下载完成后调用操作的正确方法是什么?

0 个答案:

没有答案