SftpService.java 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. package com.example.fms.service;
  2. import cn.hutool.core.io.FileUtil;
  3. import cn.hutool.core.util.IdUtil;
  4. import com.example.fms.common.model.dto.SystemFileDTO;
  5. import com.example.fms.common.model.vo.ConfigSettingVO;
  6. import com.example.fms.common.utils.FileUtils;
  7. import com.example.fms.common.utils.SFTP;
  8. import com.jcraft.jsch.*;
  9. import lombok.RequiredArgsConstructor;
  10. import lombok.extern.slf4j.Slf4j;
  11. import org.apache.poi.util.IOUtils;
  12. import org.springframework.stereotype.Service;
  13. import org.springframework.web.multipart.MultipartFile;
  14. import java.io.*;
  15. import java.util.Properties;
  16. /**
  17. * sftp配置
  18. *
  19. * @Author xiexiang
  20. * @Date 2023/6/7
  21. */
  22. @RequiredArgsConstructor
  23. @Slf4j
  24. @Service
  25. public class SftpService {
  26. /**
  27. * 建立连接
  28. *
  29. * @param s
  30. * @param configSettingVO
  31. * @throws Exception
  32. */
  33. public static void getConnect(SFTP s, ConfigSettingVO configSettingVO) throws Exception {
  34. //** 密钥的密码 */
  35. // String privateKey ="key";
  36. // /** 密钥文件路径 */
  37. // String passphrase ="path";
  38. //主机
  39. String host = configSettingVO.getName();
  40. //端口
  41. int port = 22;
  42. //用户名
  43. String username = configSettingVO.getUserName();
  44. //密码
  45. String password = configSettingVO.getPassword();
  46. //会话初始化
  47. Session session = null;
  48. //连接通道初始化
  49. Channel channel = null;
  50. //sftp操作类初始化
  51. ChannelSftp sftp = null;
  52. JSch jsch = new JSch();
  53. //设置密钥和密码
  54. //支持密钥的方式登陆,只需在jsch.getSession之前设置一下密钥的相关信息
  55. // if (privateKey != null && !"".equals(privateKey)) {
  56. // if (passphrase != null && "".equals(passphrase)) {
  57. // //设置带口令的密钥
  58. // jsch.addIdentity(privateKey, passphrase);
  59. // } else {
  60. // //设置不带口令的密钥
  61. // jsch.addIdentity(privateKey);
  62. // }
  63. // }
  64. session = jsch.getSession(username, host, port);
  65. session.setPassword(password);
  66. Properties config = new Properties();
  67. config.put("StrictHostKeyChecking", "no"); // 不验证 HostKey
  68. session.setConfig(config);
  69. try {
  70. session.connect(60000);
  71. } catch (Exception e) {
  72. if (session.isConnected())
  73. session.disconnect();
  74. }
  75. channel = session.openChannel("sftp");
  76. try {
  77. channel.connect();
  78. } catch (Exception e) {
  79. if (channel.isConnected())
  80. channel.disconnect();
  81. }
  82. sftp = (ChannelSftp) channel;
  83. s.setChannel(channel);
  84. s.setSession(session);
  85. s.setSftp(sftp);
  86. }
  87. /**
  88. * 断开连接
  89. *
  90. * @param session
  91. * @param channel
  92. * @param sftp
  93. * @throws Exception
  94. */
  95. public static void disConn(Session session, Channel channel, ChannelSftp sftp) throws Exception {
  96. if (null != sftp) {
  97. sftp.disconnect();
  98. sftp.exit();
  99. sftp = null;
  100. }
  101. if (null != channel) {
  102. channel.disconnect();
  103. channel = null;
  104. }
  105. if (null != session) {
  106. session.disconnect();
  107. session = null;
  108. }
  109. }
  110. /**
  111. * 上传文件
  112. *
  113. * @param directory 上传的目录-相对于SFPT设置的用户访问目录,
  114. * 为空则在SFTP设置的根目录进行创建文件(除设置了服务器全磁盘访问)
  115. * @param multipartFile 要上传的文件
  116. * @param configSettingVO 配置的信息
  117. * @return systemFileDTO
  118. */
  119. public static SystemFileDTO upload(String directory, MultipartFile multipartFile, ConfigSettingVO configSettingVO) throws Exception {
  120. SystemFileDTO systemFileDTO = new SystemFileDTO();
  121. SFTP s = new SFTP();
  122. //建立连接
  123. getConnect(s, configSettingVO);
  124. Session session = s.getSession();
  125. Channel channel = s.getChannel();
  126. //sftp操作类
  127. ChannelSftp sftp = s.getSftp();
  128. try {
  129. try {
  130. //进入目录
  131. sftp.cd(directory);
  132. } catch (SftpException sException) {
  133. //指定上传路径不存在
  134. if (sftp.SSH_FX_NO_SUCH_FILE == sException.id) {
  135. //创建目录
  136. sftp.mkdir(directory);
  137. //进入目录
  138. sftp.cd(directory);
  139. }
  140. }
  141. //将传入的multipartFile转为所需要的file
  142. File file = FileUtils.multipartFileToFile(multipartFile);
  143. //定义文件名随机生成
  144. String fileName = IdUtil.simpleUUID();
  145. //重命名
  146. file = FileUtil.rename(file, fileName, true, true);
  147. InputStream in = new FileInputStream(file);
  148. sftp.put(in, file.getName());
  149. in.close();
  150. FileUtils.deleteQuietly(file);
  151. //获取文件的后缀,不带“.”,必须是multipartFile类型
  152. String extName = FileUtil.extName(multipartFile.getOriginalFilename());
  153. //拼接文件完整名存入数据库表
  154. String name = fileName + "." + extName;
  155. systemFileDTO.setFileName(name);
  156. systemFileDTO.setFileLength(Long.toString(file.length()));
  157. systemFileDTO.setIsDelete(0);
  158. } catch (Exception e) {
  159. throw new Exception(e.getMessage(), e);
  160. } finally {
  161. disConn(session, channel, sftp);
  162. }
  163. return systemFileDTO;
  164. }
  165. /**
  166. * 下载文件
  167. *
  168. * @param directory 下载目录 根据SFTP设置的根目录来进行传输
  169. * @param downloadFile 下载的文件名
  170. * // * @param saveFile 存在本地的路径
  171. * @param configSettingVO
  172. * @throws Exception
  173. */
  174. public static byte[] download(String directory, String downloadFile, ConfigSettingVO configSettingVO) throws Exception {
  175. SFTP s = new SFTP();
  176. //建立连接
  177. getConnect(s, configSettingVO);
  178. Session session = s.getSession();
  179. Channel channel = s.getChannel();
  180. //sftp操作类
  181. ChannelSftp sftp = s.getSftp();
  182. try {
  183. //进入目录
  184. sftp.cd(directory);
  185. //sftp.cd(directory.substring(0, directory.indexOf("/pas")));
  186. // File file = new File(saveFile);
  187. // boolean bFile;
  188. // bFile = false;
  189. // bFile = file.exists();
  190. // if (!bFile) {
  191. // //创建目录
  192. // bFile = file.mkdirs();
  193. // }
  194. InputStream is = sftp.get(downloadFile);
  195. byte[] fileData = IOUtils.toByteArray(is);
  196. // OutputStream out = new FileOutputStream(new File(saveFile, downloadFile));
  197. // sftp.get(downloadFile, out);
  198. // out.flush();
  199. // out.close();
  200. is.close();
  201. return fileData;
  202. } catch (Exception e) {
  203. throw new Exception(e.getMessage(), e);
  204. } finally {
  205. disConn(session, channel, sftp);
  206. }
  207. }
  208. /**
  209. * 删除文件
  210. *
  211. * @param directory
  212. * @param deleteFile
  213. * @param configSettingVO
  214. * @throws Exception
  215. */
  216. public static void delete(String directory, String deleteFile, ConfigSettingVO configSettingVO) throws Exception {
  217. SFTP s = new SFTP();
  218. //建立连接
  219. getConnect(s, configSettingVO);
  220. Session session = s.getSession();
  221. Channel channel = s.getChannel();
  222. //sftp操作类
  223. ChannelSftp sftp = s.getSftp();
  224. try {
  225. //需要删除的目录的上一级
  226. sftp.cd(directory);
  227. //删除目录
  228. sftp.rm(deleteFile);
  229. } catch (Exception e) {
  230. throw new Exception(e.getMessage(), e);
  231. } finally {
  232. disConn(session, channel, sftp);
  233. }
  234. }
  235. }