我正在尝试使用JSsch库通过SFTP下载一个文件。我成功地将文件下载到本地目录。**但是,我所需要的只是直接将文件下载到浏览器中,而不给出任何本地目标路径(比如在Chrome中下载文件的方式)。我使用Spring控制器AngularJS承诺来捕获响应。下面是我的密码。
@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。这给了我一些例外,如下所示。
com.jcraft.jsch.ChannelSftp.fill(ChannelSftp.java:2909) com.jcraft.jsch.ChannelSftp.header(ChannelSftp.java:2935) com.jcraft.jsch.ChannelSftp.access$500(ChannelSftp.java:36) com.jcraft.jsch.ChannelSftp$2.read(ChannelSftp.java:1417) com.jcraft.jsch :管道关闭java.io.PipedInputStream.read(未知源)java.io.PipedInputStream.read(未知源)org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1025) org.apache.commons.io.IOUtils.copy(IOUtils.java:999) .ChannelSftp$2.read(ChannelSftp.java:1364)
发布于 2017-06-30 09:06:00
在实际读取输入流中的任何内容(存储在变量“is”中)之前,您正在断开通道和会话。请在IOUtils.copy()之后,而不是在-
is.close();
channel.disconnect();
session.disconnect();您也可以尝试直接调用
sftp.get(filename, response.getOutputSteam());看一下文档这里
发布于 2017-06-30 08:59:43
在尝试读取数据之前,无法关闭SFTP会话。
这是正确的代码:
is = sftp.get(fileName);
IOUtils.copy(is, response.getOutputStream());
channel.disconnect();
session.disconnect();
is.close();https://stackoverflow.com/questions/44842194
复制相似问题