FileController.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. package com.template.controller;
  2. import com.jcraft.jsch.*;
  3. import com.template.annotation.DESRespondSecret;
  4. import com.template.annotation.PassToken;
  5. import com.template.api.ExcelControllerAPI;
  6. import com.template.api.FileControllerAPI;
  7. import com.template.common.utils.CustomMultipartFile;
  8. import com.template.common.utils.TimeExchange;
  9. import com.template.model.pojo.SmartAccess;
  10. import com.template.model.pojo.SmartApply;
  11. import com.template.model.pojo.SmartUser;
  12. import com.template.model.pojo.SystemUser;
  13. import com.template.model.request.uploadFileResponse;
  14. import com.template.model.result.CommonResult;
  15. import com.template.model.result.PageUtils;
  16. import com.template.services.SmartAccessService;
  17. import com.template.services.SmartApplyService;
  18. import com.template.services.SmartUserService;
  19. import org.springframework.beans.factory.annotation.Autowired;
  20. import org.springframework.web.bind.annotation.RestController;
  21. import org.springframework.web.multipart.MultipartFile;
  22. import java.io.*;
  23. import java.net.*;
  24. import java.nio.charset.StandardCharsets;
  25. import java.util.ArrayList;
  26. import java.util.List;
  27. @RestController
  28. //返回参数加密注解
  29. @DESRespondSecret
  30. public class FileController implements FileControllerAPI {
  31. @Autowired
  32. private SmartAccessService smartAccessService;
  33. @Override
  34. @PassToken
  35. public CommonResult uploadFilesByCos() throws Exception {
  36. List<SmartAccess> updateUsers = new ArrayList<>();
  37. for (int i = 0;i<15000;i++) {
  38. Thread.sleep(5000);
  39. PageUtils<SmartAccess> pageDatas = smartAccessService.getPageDatas(1,120);
  40. List<SmartAccess> users = pageDatas != null && pageDatas.getList().size() > 0 ? pageDatas.getList() : new ArrayList<>();
  41. for (SmartAccess user : users) {
  42. if(org.springframework.util.StringUtils.hasText(user.getImage())){
  43. MultipartFile fileData = convert(user.getImage());
  44. String result = uploadFileStatic(fileData,"/home/images/warnings","https://xj.chuanghai-tech.com/wzimage/warnings/");
  45. if(org.springframework.util.StringUtils.hasText(result)){
  46. user.setImage(result);
  47. updateUsers.add(user);
  48. }
  49. else{
  50. String sdsd = "";
  51. }
  52. }
  53. }
  54. boolean result = smartAccessService.updateBatchById(updateUsers);
  55. }
  56. return CommonResult.ok();
  57. }
  58. //图片格式 头像 https://xj.chuanghai-tech.com/wzimage/355377EF8A889F8C9009ABA2B9F0C08A.png
  59. //告警图片 https://xj.chuanghai-tech.com/wzimage/warnings/v2-bb4414441455d233c5d963cbd4c6ba26_xld.jpeg
  60. @Override
  61. public CommonResult uploadFile(MultipartFile file) throws Exception {
  62. //限制文件类型
  63. List<String> allowedTypes = new ArrayList<>();
  64. allowedTypes.add("image/png");
  65. allowedTypes.add("image/jpeg");
  66. allowedTypes.add("image/jpg");
  67. allowedTypes.add("application/pdf");
  68. allowedTypes.add("audio/mpeg");
  69. allowedTypes.add("video/mp4");
  70. String contentType = file.getContentType();
  71. if (!allowedTypes.contains(contentType)) {
  72. return CommonResult.fail("不支持的文件类型: " + contentType);
  73. }
  74. System.out.println( "测试上传文件");
  75. uploadFileResponse result = new uploadFileResponse();
  76. System.out.println( "测试上传文件1");
  77. String url = uploadFileStatic(file,"/home/images","https://xj.chuanghai-tech.com/wzimage/");
  78. System.out.println( "测试上传文件2");
  79. if(org.springframework.util.StringUtils.hasText(url)){
  80. result.setFileUrl(url);
  81. }else{
  82. return CommonResult.fail();
  83. }
  84. return CommonResult.ok(result);
  85. }
  86. public static String uploadFileStatic(MultipartFile file, String remotePath,String urlEx) throws IOException {
  87. uploadFileResponse result = new uploadFileResponse();
  88. System.out.println("上传文件进来了");
  89. //String name = TimeExchange.DateNowTimeStamo() + "-" + file.getOriginalFilename();
  90. String name = file.getOriginalFilename().replace(" ","");
  91. String fileName = getDecodedFileNameFromUrl(name);
  92. if (fileName.contains(",")) {
  93. return null;
  94. }
  95. String user = "root"; //SFTP服务器用户名
  96. String password = "Chuanghai2023"; // SFTP服务器密码
  97. String host = "223.84.177.126"; // SFTP服务器地址
  98. System.out.println("服务器地址"+host);
  99. int port = 22; // SFTP 服务器端口
  100. String remoteDirPath = remotePath; // 远程目录路径
  101. String urlexist = urlEx + fileName;
  102. if (isImageUrlValid(urlexist)) {
  103. result.setFileUrl(urlexist);
  104. return result.getFileUrl();
  105. }
  106. //从MultipartFile对象中获取流
  107. InputStream inputStream = null;
  108. inputStream = file.getInputStream();
  109. //String downpath="/book/《Python爬虫开发与项目实战》.pdf";
  110. //String spath="C:/Users/F1339769/Desktop";
  111. JSch jsch = new JSch();
  112. Session session = null;
  113. ChannelSftp channelSftp = null;
  114. try {
  115. session = jsch.getSession(user, host, port);
  116. session.setPassword(password);
  117. session.setConfig("StrictHostKeyChecking", "no");
  118. session.connect(30000);
  119. System.out.println("连接成功");
  120. channelSftp = (ChannelSftp) session.openChannel("sftp");
  121. channelSftp.connect();
  122. // 创建远程目录
  123. String[] dirArr = remoteDirPath.split("/");
  124. String path = "";
  125. for (int i = 0; i < dirArr.length; i++) {
  126. path = path + "/" + dirArr[i];
  127. try {
  128. channelSftp.cd(path);
  129. } catch (SftpException e) {
  130. channelSftp.mkdir(path);
  131. channelSftp.cd(path);
  132. }
  133. }
  134. // 文件上传到远程服务器上
  135. channelSftp.put(inputStream, fileName);
  136. // 从远程服务器上下载文件
  137. //channelSftp.get(downpath, spath);
  138. } catch (JSchException | SftpException e) {
  139. e.printStackTrace();
  140. } finally {
  141. if (channelSftp != null) {
  142. channelSftp.disconnect();
  143. }
  144. if (session != null) {
  145. session.disconnect();
  146. }
  147. String url = urlEx + fileName;
  148. System.out.println(remoteDirPath);
  149. System.out.println(fileName);
  150. System.out.println(name);
  151. if (isImageUrlValid(urlexist)) {
  152. result.setFileUrl(url);
  153. }else {
  154. return null;
  155. }
  156. }
  157. return result.getFileUrl();
  158. }
  159. public static boolean isImageUrlValid(String imageUrl) {
  160. try {
  161. URL url = new URL(imageUrl);
  162. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  163. connection.setRequestMethod("HEAD");
  164. connection.setConnectTimeout(5000);
  165. connection.setReadTimeout(5000);
  166. int responseCode = connection.getResponseCode();
  167. // 检查HTTP状态码
  168. if (responseCode != HttpURLConnection.HTTP_OK) {
  169. return false;
  170. }
  171. // 检查Content-Type是否为图片类型
  172. String contentType = connection.getContentType();
  173. return contentType != null && contentType.startsWith("image/");
  174. } catch (IOException e) {
  175. return false;
  176. }
  177. }
  178. /**
  179. * 在线图片地址转换为MultipartFile文件
  180. *
  181. * @param imageUrl
  182. * @return
  183. * @throws IOException
  184. */
  185. public static MultipartFile convert(String imageUrl) throws IOException {
  186. System.out.println(imageUrl);
  187. URL url = new URL(imageUrl);
  188. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  189. // 设置请求头,避免被服务器拒绝
  190. connection.setRequestProperty("User-Agent", "Mozilla/5.0");
  191. try (InputStream inputStream = connection.getInputStream();
  192. ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
  193. byte[] buffer = new byte[1024];
  194. int bytesRead;
  195. while ((bytesRead = inputStream.read(buffer)) != -1) {
  196. outputStream.write(buffer, 0, bytesRead);
  197. }
  198. byte[] bytes = outputStream.toByteArray();
  199. String fileName = extractFilenameFromUrl(imageUrl);
  200. String contentType = determineContentTypeFromUrl(imageUrl);
  201. return new CustomMultipartFile(bytes, fileName, contentType);
  202. } finally {
  203. connection.disconnect();
  204. }
  205. }
  206. /**
  207. * 从URL中提取文件名
  208. */
  209. private static String extractFilenameFromUrl(String imageUrl) {
  210. try {
  211. String path = new URL(imageUrl).getPath();
  212. String filename = path.substring(path.lastIndexOf('/') + 1);
  213. // 如果文件名没有扩展名,添加默认扩展名
  214. if (!filename.contains(".")) {
  215. filename += ".jpg";
  216. }
  217. return filename;
  218. } catch (Exception e) {
  219. return "downloaded_image.jpg";
  220. }
  221. }
  222. /**
  223. * 根据URL推断内容类型
  224. */
  225. private static String determineContentTypeFromUrl(String imageUrl) {
  226. if (imageUrl.toLowerCase().endsWith(".jpg") || imageUrl.toLowerCase().endsWith(".jpeg")) {
  227. return "image/jpeg";
  228. } else if (imageUrl.toLowerCase().endsWith(".png")) {
  229. return "image/png";
  230. } else if (imageUrl.toLowerCase().endsWith(".gif")) {
  231. return "image/gif";
  232. } else if (imageUrl.toLowerCase().endsWith(".bmp")) {
  233. return "image/bmp";
  234. } else if (imageUrl.toLowerCase().endsWith(".webp")) {
  235. return "image/webp";
  236. } else {
  237. return "image/jpeg"; // 默认类型
  238. }
  239. }
  240. public static String getDecodedFileNameFromUrl(String url) {
  241. try {
  242. // 提取URL中的文件名部分
  243. String fileName = url.substring(url.lastIndexOf('/') + 1);
  244. // 如果有查询参数,去掉查询参数部分
  245. if (fileName.contains("?")) {
  246. fileName = fileName.substring(0, fileName.indexOf("?"));
  247. }
  248. // URL解码
  249. return URLDecoder.decode(fileName, "UTF-8");
  250. } catch (Exception e) {
  251. e.printStackTrace();
  252. return null;
  253. }
  254. }
  255. }