工具类
@Slf4j
@Component
public class SFTPUtils {@Resourceprivate SftpConfig sftpConfig;Session session = null;Channel channel = null;public String uploadFileSFTP(String fileUrl) {if (StringUtils.isBlank(fileUrl)) {throw new RuntimeException("图片路径不能为空");}String[] split = fileUrl.split("=");String fileName = split[split.length - 1];URL url = null;try {url = new URL(fileUrl);} catch (MalformedURLException e) {e.printStackTrace();}ChannelSftp chSftp = null;try {String dst = sftpConfig.getVpsUrl() + LocalDate.now().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)) + "/"; chSftp = this.getChannel(60000);this.createDir(dst, chSftp);chSftp.put(url.openStream(), dst + fileName, ChannelSftp.OVERWRITE); return dst + fileName;} catch (Exception e) {e.printStackTrace();log.error(e.getMessage());} finally {if (null != chSftp) {chSftp.quit();}if (channel != null) {channel.disconnect();}if (session != null) {session.disconnect();}}return null;}public String uploadFileSFTP(InputStream inputStream) {ChannelSftp chSftp = null;try {String dst = sftpConfig.getVpsUrl() + LocalDate.now().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)) + "/"; chSftp = this.getChannel(60000);this.createDir(dst, chSftp);String fileUrl = dst + System.currentTimeMillis() + ".png";chSftp.put(inputStream, fileUrl, ChannelSftp.OVERWRITE); return fileUrl;} catch (Exception e) {e.printStackTrace();log.error(e.getMessage());} finally {if (null != chSftp) {chSftp.quit();}if (channel != null) {channel.disconnect();}if (session != null) {session.disconnect();}}return null;}public ChannelSftp getChannel(int timeout) throws JSchException {JSch jsch = new JSch();session = jsch.getSession(sftpConfig.getFtpUserName(), sftpConfig.getFtpHost(), sftpConfig.getPortL());session.setPassword(sftpConfig.getFtpPassword());Properties config = new Properties();config.put("StrictHostKeyChecking", "no");session.setConfig(config); session.setTimeout(timeout); session.connect(); channel = session.openChannel("sftp"); channel.connect(); return (ChannelSftp) channel;}private void createDir(String createpath, ChannelSftp sftp) {try {sftp.mkdir(createpath);} catch (SftpException e) {log.error(createpath + "文件夹已存在");}}}
配置类
yml文件为
test:sftp:ftpHost: 127.0.0.1portL: 22ftpUserName: rootftpPassword: rootvpsUrl: /data/test/img @Data
@Configuration
@ConfigurationProperties(prefix = "test.sftp")
public class SftpConfig {private String ftpHost;private Integer portL;private String ftpUserName;private String ftpPassword;private String vpsUrl;}
调用
@Resourceprivate SFTPUtils sftpUtils;
String fqFm = sftpUtils.uploadFileSFTP('图片url');