XPages:如何创建从文件系统下载文件的链接 [英] XPages: How to create link to download file from filesystem

查看:108
本文介绍了XPages:如何创建从文件系统下载文件的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个文件夹中有一个pdf文件,我想从xpage下载它。

i have a pdf file in a folder and i want to download it from an xpage.

通常这只是这样的HTML:

Normally this is just html like this:

<a href='file://10.1.0.2/folder1/myfile.pdf'>click and download</a>

我测试了它在一个简单的html文件中使用这一行。
在我的Xpage中,我创建了一个计算字段(HTML显示),并添加了< a>作为价值。我在悬停时看到正确的链接,但点击没有任何反应。有什么问题?

I tested that it works using this line in a simple html file. In my Xpage I created a computed field (HTML display) and i added the < a > as value. I see the correct link on hover but on click nothing happens. What is the problem?

Thnx

推荐答案

我最近解决了通过编写下载servlet作为无头XPage来解决这类问题。对于链接添加onclick事件:

I have recently solved this kind of problem by writing a download "servlet" as a headless XPage. For link add onclick event:

sessionScope.put("filepath", file);
context.redirectToPage("/_download.xsp") 

_ download page有 beforeRenderResponse 事件 facesContext.responseComplete()并在 afterRenderResponse 中调用读取文件的java代码并写入输出流。这样的事情:

_download page has beforeRenderResponse event facesContext.responseComplete() and in afterRenderResponse call a java code that reads the file and writes to the output stream. Something like this:

if (sessionScope.containsKey("filepath")){
    FileDownload.sendFile(sessionScope.filepath);
}

java class:

java class:

public class FileDownload {
public static void sendFile(String filepath) {
    File file = new File(filepath);
    if (file.exists()) {
        ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletResponse response = (HttpServletResponse) ec.getResponse();
        response.setContentType(MIME(filepath)); // figure out the type from extension or else

        OutputStream out;
        try {
            // for the download dialog
            response.setHeader("Content-disposition",
                    "attachment; filename*=utf-8''" + java.net.URLEncoder.encode(file.getName(), "UTF-8").replace("+", "%20"));
            out = response.getOutputStream();
            FileInputStream in = new FileInputStream(file);
            byte[] buffer = new byte[4096];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            in.close();
            out.flush();
        } catch (IOException e) {

        }
    }
}
}

不幸的是,对于非常大的文件(1Gb左右),它变得很慢,内存大约是文件大小的两倍,但我不知道我能在这里优化什么。我试图在循环中调用 out.flush(),但它没有效果。

Unfortunately for very large files (1Gb or so) it becomes slow, also takes memory about twice the size of the file, but I'm not sure what could I optimize here. I've tried to call out.flush() within the loop, but it has no effect.

这篇关于XPages:如何创建从文件系统下载文件的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆