首先从sftp文件服务器获取文件流(这儿文件流也可以按需获取),利用IO工具复制文件流给前端返回。
@Override
public void distributeAttachment(Long id, HttpServletResponse response) {
//查询地址路径
EnclosureUpload enclosureUpload = enclosureUploadMapper.selectById(id);
SftpUtil sftpUtil = new SftpUtil();
try {
ChannelSftp channel = sftpUtil.getChannel(ftpConfig.getHost2(), Integer.parseInt(ftpConfig.getPort2()), ftpConfig.getUser2(), ftpConfig.getPassword2());
InputStream inputStream = channel.get(enclosureUpload.getAddress());
String fileName = URLEncoder.encode(enclosureUpload.getFileName(), Charsets.UTF_8.name());
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
} finally {
try {
sftpUtil.closeChannel();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}