java - 如何读取服务器文件并将其作为可下载文件在 XPage 的用户 Web 浏览器中输出

标签 java download xpages output

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

场景是

  • 用户单击 XPage 中的链接
  • 请求被发送到服务器,该服务器读取服务器文件系统中的预定义文件
  • 该文件作为可下载文件在网络浏览器中返回给用户。

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

    这是在 SSJS 上完成还是在 Java 中完成都没有关系。

    我真的很喜欢一些代码

    最佳答案

    这是我想出的代码,不是生产代码。

        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 中调用下载方法

    关于java - 如何读取服务器文件并将其作为可下载文件在 XPage 的用户 Web 浏览器中输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14819257/

    相关文章:

    java - 使用Spring Data Gemfire时的@Region注释

    java - 如何使用 Jackson 将其序列化为 xml?

    java - 数组 - 输出必须是一年中的月份

    audio - Windows CMD提示Youtube-Dl。无法将多个youtube mp3播放列表下载到特定的文件夹中

    android - Quickblox,如何使用自定义对象从下载的文件中获取用户标识

    java - 托管 Bean 丢失导入语句

    java - Xpages "Views"with beans : Categorize, 排序、搜索

    java - Hibernate 4 保存不起作用

    linux - 任何人都可以向我发送适用于 Linux 的 Coldfusion 11 的下载链接吗?

    java - 在Java中读取sessionScope变量?