如何读取服务器文件并将其作为可下载文件输出到XPage的用户Web浏览器中 [英] How to read a server file and output that as a downloadable file in users web browser in XPages

查看:313
本文介绍了如何读取服务器文件并将其作为可下载文件输出到XPage的用户Web浏览器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在服务器上读取文件(在网络上不可用),并将其作为可下载文件输出给用户。

I need to read a file (that is not available on web) on the server and output it to the user as a downloadable file.

该方案为


  1. 用户单击XPage中的链接

  2. 请求发送到读取服务器文件系统中的预定义文件

  3. 该文件作为webbrowser中的可下载文件带回用户。

服务器上的文件可以是任何格式,例如.pdf,.exe,.doc等

The file on the server can be in any format, e.g .pdf, .exe, .doc etc

无论是否在SSJS或java中完成。

It does not matter if this is done on SSJS or in java.

我真的会感谢一些代码

推荐答案

这是代码我想出了这样做,def不是生产代码。

Here is the code I came up with to do this, def not production code.

    public static byte[] grabFile(String readFile) throws IOException {

        File file = new File(readFile);
        ByteArrayOutputStream ous = new ByteArrayOutputStream();
        InputStream ios = new FileInputStream(file);

        try {
            byte []buffer = new byte[4096];

            int read = 0;
            while ( (read = ios.read(buffer)) != -1 ) {
                ous.write(buffer, 0, read);
            }
        } finally { 
            try {
                 if ( ous != null ) 
                     ous.close();
            } catch ( IOException e) {
            }

            try {
                 if ( ios != null ) 
                      ios.close();
            } catch ( IOException e) {
            }
        }
        return ous.toByteArray();
    }

 public static void download() throws IOException {
        byte[] data = grabFile("\\\\server\\path\\to\\file.pdf");
        HttpServletResponse response = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
        response.reset(); 
        response.setContentType("application/pdf"); 
        response.setHeader("Content-disposition", "attachment; filename=\"filename.pdf\"");
        OutputStream output = response.getOutputStream();
        output.write(data);
        output.close();
        FacesContext.getCurrentInstance().responseComplete(); 
    }

然后只需从Xpage的beforeRenderResponse调用下载方法

Then just call the download method from the beforeRenderResponse of your Xpage

这篇关于如何读取服务器文件并将其作为可下载文件输出到XPage的用户Web浏览器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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