SftpService.java 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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();
  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. * @param directory 上传的目录-相对于SFPT设置的用户访问目录,
  113. * 为空则在SFTP设置的根目录进行创建文件(除设置了服务器全磁盘访问)
  114. * @param multipartFile 要上传的文件
  115. * @param configSettingVO 配置的信息
  116. * @return systemFileDTO
  117. */
  118. public static SystemFileDTO upload(String directory, MultipartFile multipartFile, ConfigSettingVO configSettingVO) throws Exception {
  119. SystemFileDTO systemFileDTO = new SystemFileDTO();
  120. SFTP s = new SFTP();
  121. //建立连接
  122. getConnect(s, configSettingVO);
  123. Session session = s.getSession();
  124. Channel channel = s.getChannel();
  125. //sftp操作类
  126. ChannelSftp sftp = s.getSftp();
  127. try {
  128. try{
  129. //进入目录
  130. sftp.cd(directory);
  131. }catch(SftpException sException){
  132. //指定上传路径不存在
  133. if(sftp.SSH_FX_NO_SUCH_FILE == sException.id){
  134. //创建目录
  135. sftp.mkdir(directory);
  136. //进入目录
  137. sftp.cd(directory);
  138. }
  139. }
  140. //将传入的multipartFile转为所需要的file
  141. File file = FileUtils.multipartFileToFile(multipartFile);
  142. //定义文件名随机生成
  143. String fileName = IdUtil.simpleUUID();
  144. //重命名
  145. file = FileUtil.rename(file, fileName, true, true);
  146. InputStream in= new FileInputStream(file);
  147. sftp.put(in, file.getName());
  148. in.close();
  149. //获取文件的后缀,不带“.”,必须是multipartFile类型
  150. String extName = FileUtil.extName(multipartFile.getOriginalFilename());
  151. //拼接文件完整名存入数据库表
  152. String name = fileName + "." + extName;
  153. systemFileDTO.setFileName(name);
  154. systemFileDTO.setFileLength(Long.toString(file.length()));
  155. systemFileDTO.setIsDelete(0);
  156. } catch (Exception e) {
  157. throw new Exception(e.getMessage(),e);
  158. } finally {
  159. disConn(session, channel, sftp);
  160. }
  161. return systemFileDTO;
  162. }
  163. /**
  164. * 下载文件
  165. * @param directory 下载目录 根据SFTP设置的根目录来进行传输
  166. * @param downloadFile 下载的文件名
  167. // * @param saveFile 存在本地的路径
  168. * @param configSettingVO
  169. * @throws Exception
  170. */
  171. public static byte[] download(String directory, String downloadFile, ConfigSettingVO configSettingVO) throws Exception {
  172. SFTP s = new SFTP();
  173. //建立连接
  174. getConnect(s, configSettingVO);
  175. Session session = s.getSession();
  176. Channel channel = s.getChannel();
  177. //sftp操作类
  178. ChannelSftp sftp = s.getSftp();
  179. try {
  180. //进入目录
  181. sftp.cd(directory);
  182. // File file = new File(saveFile);
  183. // boolean bFile;
  184. // bFile = false;
  185. // bFile = file.exists();
  186. // if (!bFile) {
  187. // //创建目录
  188. // bFile = file.mkdirs();
  189. // }
  190. InputStream is = sftp.get(downloadFile);
  191. byte[] fileData = IOUtils.toByteArray(is);
  192. // OutputStream out = new FileOutputStream(new File(saveFile, downloadFile));
  193. // sftp.get(downloadFile, out);
  194. // out.flush();
  195. // out.close();
  196. is.close();
  197. return fileData;
  198. } catch (Exception e) {
  199. throw new Exception(e.getMessage(), e);
  200. } finally {
  201. disConn(session, channel, sftp);
  202. }
  203. }
  204. /**
  205. * 删除文件
  206. * @param directory
  207. * @param deleteFile
  208. * @param configSettingVO
  209. * @throws Exception
  210. */
  211. public static void delete(String directory, String deleteFile, ConfigSettingVO configSettingVO) throws Exception{
  212. SFTP s = new SFTP();
  213. //建立连接
  214. getConnect(s, configSettingVO);
  215. Session session = s.getSession();
  216. Channel channel = s.getChannel();
  217. //sftp操作类
  218. ChannelSftp sftp = s.getSftp();
  219. try {
  220. //需要删除的目录的上一级
  221. sftp.cd(directory);
  222. //删除目录
  223. sftp.rm(deleteFile);
  224. } catch (Exception e){
  225. throw new Exception(e.getMessage(), e);
  226. } finally {
  227. disConn(session, channel, sftp);
  228. }
  229. }
  230. }