代码之家  ›  专栏  ›  技术社区  ›  BIndu_Madhav

将文件从SFTP直接下载到HTTP响应,而不使用中间文件

  •  1
  • BIndu_Madhav  · 技术社区  · 7 年前

    我试图使用Java JSsch库通过SFTP下载一个文件。我成功地将文件下载到本地目录**但是,我只需要将文件直接下载到浏览器,而不需要提供任何本地目标路径(例如文件在Chrome中的下载方式)。我正在使用Spring控制器AngularJS Promise捕捉响应。下面是我的代码。

    @RequestMapping(value = "/downloadAttachment", method = RequestMethod.POST,
                    produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void downloadAttachment(
            @RequestParam(value = "fileName") String fileName,
            @RequestParam(value = "filePath") String filePath,
            @RequestParam(value = "fileId") String fileId,
            HttpServletResponse response, Locale locale) throws Exception {
        InputStream is = null;
        if(!fileName.isEmpty() && !filePath.isEmpty() && !fileId.isEmpty()){
            String directory = filePath;
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            JSch ssh = new JSch();
            Session session = ssh.getSession(sftpLogin, sftpAddress, 22);
            session.setConfig(config);
            session.setPassword(sftpPassword);
            session.connect();
            logger.info("Connection to server established");
            Channel channel = session.openChannel("sftp");
            channel.connect();
    
            ChannelSftp sftp = (ChannelSftp) channel;
            sftp.cd(directory);
            is = sftp.get(fileName);
            channel.disconnect();
            session.disconnect();
        }
        IOUtils.copy(is, response.getOutputStream());
        is.close();
        response.getOutputStream().close();
        response.flushBuffer();
    }
    

    MediaType.APPLICATION_OCTET_STREAM_VALUE

    java.io。IOException:管道关闭 fill(ChannelSftp.java:2909) jcraft.jsch.ChannelSftp.header(ChannelSftp.java:2935) access$500(ChannelSftp.java:36) jcraft.jsch.ChannelSftp$2.read(ChannelSftp.java:1417) 复制(IOUtils.java:999)

    2 回复  |  直到 7 年前
        1
  •  2
  •   Martin Prikryl    7 年前

    在尝试读取数据之前,无法关闭SFTP会话。

    is = sftp.get(fileName);
    IOUtils.copy(is, response.getOutputStream());
    channel.disconnect();
    session.disconnect();
    is.close();
    
        2
  •  1
  •   Tarun Bansal    7 年前

    在从输入流(存储在变量“is”中)实际读取任何内容之前,您正在断开通道和会话的连接。请在IOUtils后拨打以下电话。复制()而不是之前-

    is.close();
    channel.disconnect();
    session.disconnect();
    

    你也可以直接打电话

    sftp.get(filename, response.getOutputSteam());
    

    查看文档 here