我试图使用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)