当前位置:   article > 正文

java代码实现linux文件的上传与下载修改_java上传文件到linux服务器替换文件

java上传文件到linux服务器替换文件

一、下载linux中的文件

1.controller类

  1. @Tag(name = "读取配置文件")
  2. @Schema(description = "读取配置文件")
  3. @PostMapping("/file")
  4. public OutputStream file(
  5. @RequestBody @Validated UpdateConfigDto updateConfig, HttpServletResponse response) {
  6. return manageClusterServer.readLinux(updateConfig, response);
  7. }

2.server类

String user = updateConfigDto.getSshUser();
String host = updateConfigDto.getIp();
int port = updateConfigDto.getSshPort();
String dir = getDir(updateConfigDto);
return FtpUtils.downLoad(user, host, port, dir, response);

3.sftp工具

  1. package com.skyable.deploy.utils;
  2. import cn.hutool.core.io.IoUtil;
  3. import com.jcraft.jsch.*;
  4. import com.skyable.common.constants.exception.DeployExcpConstants;
  5. import com.skyable.common.exceptions.BusinessException;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.apache.commons.io.FileUtils;
  8. import org.springframework.web.multipart.MultipartFile;
  9. import javax.servlet.ServletOutputStream;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import java.io.*;
  13. import java.util.Properties;
  14. /**
  15. * @author laoYou
  16. */
  17. @Slf4j
  18. public class FtpUtils {
  19. /** 超时时间 */
  20. private static final String TIME_OUT = "6000";
  21. /** sftp对象 */
  22. private static ChannelSftp channelSftp = null;
  23. /** 会话 */
  24. private static Session session = null;
  25. /**
  26. * 判断ftp是否已连接
  27. *
  28. * @return
  29. */
  30. public static boolean isOpen() {
  31. try {
  32. channelSftp = new ChannelSftp();
  33. channelSftp.getServerVersion();
  34. return true;
  35. } catch (Exception e) {
  36. return false;
  37. }
  38. }
  39. /** ftp链接 */
  40. public static void connectionFtp(String user, String ip, Integer port) {
  41. try {
  42. boolean open = isOpen();
  43. if (!open) {
  44. // 创建JSch对象
  45. JSch jsch = new JSch();
  46. String priKeyBasePath = "/root/.ssh/id_rsa";
  47. jsch.addIdentity(priKeyBasePath);
  48. // 通过 用户名,主机地址,端口 获取一个Session对象
  49. session = jsch.getSession(user, ip, port);
  50. // session.setPassword("root");
  51. // 为Session对象设置properties
  52. Properties config = new Properties();
  53. config.put("StrictHostKeyChecking", "no");
  54. session.setConfig(config);
  55. // 设置超时时间
  56. session.setTimeout(Integer.parseInt(TIME_OUT));
  57. // 建立链接
  58. session.connect();
  59. // 打开SFTP通道
  60. // 通道
  61. Channel channel = session.openChannel("sftp");
  62. // 建立SFTP通道的连接
  63. channel.connect();
  64. channelSftp = (ChannelSftp) channel;
  65. }
  66. } catch (Exception e) {
  67. log.error("{}", e.getMessage());
  68. }
  69. }
  70. public static void getInputStream(String uploadPath, InputStream inputStream, String fileName) {
  71. try {
  72. File files = new File("/home/test/d.conf");
  73. FileUtils.copyInputStreamToFile(inputStream, files);
  74. FileInputStream io = null;
  75. try {
  76. log.info("上传文件");
  77. if (null == channelSftp || channelSftp.isClosed()) {
  78. log.error("链接丢失");
  79. throw new BusinessException(
  80. DeployExcpConstants.ERROR_CODE_MANAGE_CONFIG_NO_SFTP,
  81. DeployExcpConstants.ERROR_MSG_MANAGE_CONFIG_NO_SFTP);
  82. }
  83. if (isExistDir(uploadPath)) {
  84. channelSftp.cd(uploadPath);
  85. } else {
  86. createDir(uploadPath, channelSftp);
  87. }
  88. io = new FileInputStream(files);
  89. channelSftp.put(io, fileName);
  90. log.info("上传文件");
  91. } catch (Exception e) {
  92. log.error("{}", e.getMessage());
  93. } finally {
  94. if (null != io) {
  95. try {
  96. io.close();
  97. } catch (IOException e) {
  98. e.printStackTrace();
  99. }
  100. }
  101. disconnect();
  102. }
  103. } catch (IOException e) {
  104. e.printStackTrace();
  105. }
  106. }
  107. /**
  108. * 上传文件到 linux
  109. *
  110. * @param dir 上传文件地址
  111. * @param file 本地文件地址
  112. */
  113. public static void uploadFile(String dir, MultipartFile file) {
  114. try {
  115. File files = new File("/work/a.txt");
  116. if (!files.exists()) {
  117. files.createNewFile();
  118. }
  119. FileUtils.copyInputStreamToFile(file.getInputStream(), files);
  120. FileInputStream io = null;
  121. try {
  122. if (null == channelSftp || channelSftp.isClosed()) {
  123. throw new BusinessException(
  124. DeployExcpConstants.ERROR_CODE_MANAGE_CONFIG_NO_SFTP,
  125. DeployExcpConstants.ERROR_MSG_MANAGE_CONFIG_NO_SFTP);
  126. }
  127. io = new FileInputStream(files);
  128. channelSftp.put(io, dir);
  129. } catch (Exception e) {
  130. log.error("{}", e.getMessage());
  131. throw new BusinessException(
  132. DeployExcpConstants.ERROR_CODE_MANAGE_CONFIG_NO_SFTP, e.getMessage());
  133. } finally {
  134. if (null != io) {
  135. try {
  136. io.close();
  137. log.info("文件上传成功!!!");
  138. files.delete();
  139. } catch (IOException e) {
  140. e.printStackTrace();
  141. }
  142. }
  143. disconnect();
  144. }
  145. } catch (IOException e) {
  146. e.printStackTrace();
  147. }
  148. }
  149. public static boolean isExistDir(String directory) {
  150. boolean isDirExistFlag = false;
  151. try {
  152. SftpATTRS sftpAttrS = channelSftp.lstat(directory);
  153. isDirExistFlag = true;
  154. return sftpAttrS.isDir();
  155. } catch (Exception e) {
  156. if ("no such file".equals(e.getMessage().toLowerCase())) {
  157. isDirExistFlag = false;
  158. }
  159. }
  160. return isDirExistFlag;
  161. }
  162. /**
  163. * @param createpath 文件目录地址
  164. */
  165. public static void createDir(String createpath, ChannelSftp sftp) throws Exception {
  166. try {
  167. String[] pathArry = createpath.split("/");
  168. StringBuffer filePath = new StringBuffer("/");
  169. for (String path : pathArry) {
  170. if ("".equals(path)) {
  171. continue;
  172. }
  173. filePath.append(path).append("/");
  174. if (isExistDir(filePath.toString())) {
  175. sftp.cd(filePath.toString());
  176. } else {
  177. // 建立目录
  178. sftp.mkdir(filePath.toString());
  179. // 进入并设置为当前目录
  180. sftp.cd(filePath.toString());
  181. }
  182. }
  183. channelSftp.cd(createpath);
  184. } catch (SftpException e) {
  185. log.error("创建目录失败,{}", e.getMessage());
  186. }
  187. }
  188. /** 关闭ftp */
  189. public static void disconnect() {
  190. if (channelSftp.isConnected()) {
  191. session.disconnect();
  192. channelSftp.disconnect();
  193. }
  194. }
  195. /**
  196. * 从linux下载文件
  197. *
  198. * @param user
  199. * @param host
  200. * @param port
  201. * @param dir
  202. */
  203. public static OutputStream downLoad(
  204. String user, String host, Integer port, String dir, HttpServletResponse response) {
  205. try {
  206. JSch jsch = new JSch();
  207. String priKeyBasePath = "/root/.ssh/id_rsa";
  208. jsch.addIdentity(priKeyBasePath);
  209. Session session = jsch.getSession(user, host, port);
  210. // 避免SSH 的公钥检查
  211. session.setConfig("StrictHostKeyChecking", "no");
  212. //session.setPassword("");
  213. session.connect();
  214. ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  215. sftpChannel.connect();
  216. InputStream inputStream = sftpChannel.get(dir);
  217. OutputStream outPutStream = response.getOutputStream();
  218. // 直接传给前端
  219. outPutStream.write(IoUtil.readBytes(inputStream));
  220. outPutStream.flush();
  221. outPutStream.close();
  222. return outPutStream;
  223. } catch (JSchException | SftpException | IOException e) {
  224. e.printStackTrace();
  225. }
  226. disconnect();
  227. return null;
  228. }
  229. }

二、文件上传到linux

1.controller类

实体类与文件一块传参

  1. @Tag(name = "上传配置file")
  2. @Schema(description = "上传配置file")
  3. @PostMapping("/update/file")
  4. public ResponseResult<?> updateFiles(
  5. @RequestParam(value = "dtoJson") String updateConfigDto,
  6. @RequestParam(value = "file") MultipartFile file,
  7. HttpServletRequest request,
  8. HttpServletResponse response) {
  9. Gson gson = new Gson();
  10. UpdateConfigDto configDto = gson.fromJson(updateConfigDto, UpdateConfigDto.class);
  11. return manageClusterServer.updateFile(configDto, request, file, response);
  12. }

2.server类

  1. @Override
  2. public ResponseResult<?> updateFile(
  3. UpdateConfigDto configDto,
  4. HttpServletRequest request,
  5. MultipartFile file,
  6. HttpServletResponse response) {
  7. String user = configDto.getSshUser();
  8. String ip = configDto.getIp();
  9. Integer port = configDto.getSshPort();
  10. String dir = getDir(configDto);
  11. try {
  12. FtpUtils.connectionFtp(user, ip, port);
  13. FtpUtils.uploadFile(dir, file);
  14. } catch (Exception e) {
  15. return ResponseResult.error(
  16. DeployExcpConstants.ERROR_CODE_MANAGE_CONFIG_FILE,
  17. DeployExcpConstants.ERROR_MSG_MANAGE_CONFIG_FILE);
  18. }
  19. return ResponseResult.success();
  20. }

三、上传超1G的大文件方法

配置文件增加Tomcat的文件限制

  1. server:
  2. port: 8099
  3. tomcat:
  4. max-swallow-size: 5GB
  5. spring:
  6. application:
  7. name: cloud-deploy
  8. servlet:
  9. multipart:
  10. max-file-size: -1 # 设置单个文件的大小为5GB
  11. max-request-size: -1 # 设置总上传的数据大小为50GB

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/715591
推荐阅读
相关标签
  

闽ICP备14008679号