CommonController.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. package com.ruoyi.web.controller.common;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.ruoyi.common.config.RuoYiConfig;
  4. import com.ruoyi.common.constant.Constants;
  5. import com.ruoyi.common.core.domain.AjaxResult;
  6. import com.ruoyi.common.utils.QRCodeUtils;
  7. import com.ruoyi.common.utils.SecurityUtils;
  8. import com.ruoyi.common.utils.StringUtils;
  9. import com.ruoyi.common.utils.file.FileUploadUtils;
  10. import com.ruoyi.common.utils.file.FileUtils;
  11. import com.ruoyi.common.utils.file.ImageUtils;
  12. import com.ruoyi.framework.config.ServerConfig;
  13. import org.slf4j.Logger;
  14. import org.slf4j.LoggerFactory;
  15. import org.springframework.beans.factory.annotation.Autowired;
  16. import org.springframework.http.MediaType;
  17. import org.springframework.web.bind.annotation.GetMapping;
  18. import org.springframework.web.bind.annotation.PostMapping;
  19. import org.springframework.web.bind.annotation.RequestMapping;
  20. import org.springframework.web.bind.annotation.RestController;
  21. import org.springframework.web.multipart.MultipartFile;
  22. import javax.servlet.http.HttpServletRequest;
  23. import javax.servlet.http.HttpServletResponse;
  24. import java.io.File;
  25. import java.nio.file.Path;
  26. import java.nio.file.Paths;
  27. import java.util.ArrayList;
  28. import java.util.List;
  29. /**
  30. * 通用请求处理
  31. *
  32. * @author ruoyi
  33. */
  34. @RestController
  35. @RequestMapping("/common")
  36. public class CommonController {
  37. private static final Logger log = LoggerFactory.getLogger(CommonController.class);
  38. @Autowired
  39. private ServerConfig serverConfig;
  40. private static final String FILE_DELIMETER = ",";
  41. /**
  42. * 通用下载请求
  43. *
  44. * @param fileName 文件名称
  45. * @param delete 是否删除
  46. */
  47. @GetMapping("/download")
  48. public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
  49. try {
  50. if (!FileUtils.checkAllowDownload(fileName)) {
  51. throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
  52. }
  53. String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
  54. String filePath = RuoYiConfig.getDownloadPath() + fileName;
  55. response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
  56. FileUtils.setAttachmentResponseHeader(response, realFileName);
  57. FileUtils.writeBytes(filePath, response.getOutputStream());
  58. if (delete) {
  59. FileUtils.deleteFile(filePath);
  60. }
  61. } catch (Exception e) {
  62. log.error("下载文件失败", e);
  63. }
  64. }
  65. /**
  66. * 通用上传请求(单个)
  67. */
  68. @PostMapping("/upload")
  69. public AjaxResult uploadFile(MultipartFile file) throws Exception {
  70. try {
  71. // 上传文件路径
  72. String filePath = RuoYiConfig.getUploadPath();
  73. String thumbnailPath = "";
  74. // 上传并返回新文件名称
  75. String fileName = FileUploadUtils.upload(filePath, file);
  76. String url = serverConfig.getUrl() + fileName;
  77. String fileType = FileUtils.getFileType(file);
  78. if ("video".equalsIgnoreCase(fileType)) {
  79. thumbnailPath = fileName.replace("/profile", RuoYiConfig.getProfile());
  80. int dotIndex = thumbnailPath.lastIndexOf(".");
  81. if (dotIndex != -1) {
  82. thumbnailPath = thumbnailPath.substring(0, dotIndex) + ".jpg";
  83. } else {
  84. thumbnailPath = thumbnailPath + ".jpg"; // 如果没有后缀,直接加 .jpg
  85. }
  86. FileUtils.screenShots(fileName.replace("/profile", RuoYiConfig.getProfile()), thumbnailPath, "00:00:01");
  87. }
  88. if ("image".equalsIgnoreCase(fileType)) {
  89. //获取用户名
  90. String username = SecurityUtils.getUsername();
  91. // 原始文件
  92. if (fileName.contains("/profile/upload")) {
  93. fileName = fileName.replace("/profile/upload", "");
  94. }
  95. File sourceFile = new File(filePath + fileName);
  96. //图片添加水印
  97. String watermarkFileName = "watermark_" + fileName;
  98. File destFile = new File(filePath + fileName);
  99. // 加水印
  100. ImageUtils.addWatermark(sourceFile, destFile, "@" + username, "次元时代-ACG爱好者社区");
  101. fileName = watermarkFileName;
  102. }
  103. AjaxResult ajax = AjaxResult.success();
  104. ajax.put("url", url);
  105. ajax.put("fileName", fileName);
  106. ajax.put("newFileName", FileUtils.getName(fileName));
  107. ajax.put("originalFilename", file.getOriginalFilename());
  108. ajax.put("fileType", fileType);
  109. ajax.put("thumbnailPath", thumbnailPath);
  110. return ajax;
  111. } catch (Exception e) {
  112. return AjaxResult.error(e.getMessage());
  113. }
  114. }
  115. // /**
  116. // * 通用上传请求(单个)
  117. // */
  118. // @PostMapping("/upload")
  119. // public AjaxResult uploadFile(MultipartFile file) throws Exception {
  120. // try {
  121. // // 上传文件路径
  122. // String filePath = RuoYiConfig.getUploadPath();
  123. // String thumbnailPath = "";
  124. // // 上传并返回新文件名称
  125. // String fileName = OssUtils.uploadMultipartFile(file);
  126. // System.out.println(fileName);
  127. // String url = OssUtils.getOssFilePath(fileName);
  128. // String fileType = FileUtils.getFileType(file);
  129. // if ("video".equalsIgnoreCase(fileType)) {
  130. // thumbnailPath = fileName;
  131. // int dotIndex = thumbnailPath.lastIndexOf(".");
  132. // if (dotIndex != -1) {
  133. // thumbnailPath = thumbnailPath.substring(0, dotIndex) + ".jpg";
  134. // } else {
  135. // thumbnailPath = thumbnailPath + ".jpg"; // 如果没有后缀,直接加 .jpg
  136. // }
  137. // FileUtils.screenShots(fileName.replace("/profile", RuoYiConfig.getProfile()), thumbnailPath, "00:00:01");
  138. // }
  139. // AjaxResult ajax = AjaxResult.success();
  140. // ajax.put("url", url);
  141. // ajax.put("fileName", fileName);
  142. // ajax.put("newFileName", FileUtils.getName(fileName));
  143. // ajax.put("originalFilename", file.getOriginalFilename());
  144. // ajax.put("fileType", fileType);
  145. // ajax.put("thumbnailPath", thumbnailPath);
  146. // return ajax;
  147. // } catch (Exception e) {
  148. // return AjaxResult.error(e.getMessage());
  149. // }
  150. // }
  151. /**
  152. * 通用上传请求(多个)
  153. */
  154. @PostMapping("/uploads")
  155. public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception {
  156. try {
  157. // 上传文件路径
  158. String filePath = RuoYiConfig.getUploadPath();
  159. List<String> urls = new ArrayList<String>();
  160. List<String> fileNames = new ArrayList<String>();
  161. List<String> newFileNames = new ArrayList<String>();
  162. List<String> originalFilenames = new ArrayList<String>();
  163. for (MultipartFile file : files) {
  164. // 上传并返回新文件名称
  165. String fileName = FileUploadUtils.upload(filePath, file);
  166. String url = serverConfig.getUrl() + fileName;
  167. urls.add(url);
  168. fileNames.add(fileName);
  169. newFileNames.add(FileUtils.getName(fileName));
  170. originalFilenames.add(file.getOriginalFilename());
  171. }
  172. AjaxResult ajax = AjaxResult.success();
  173. ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
  174. ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
  175. ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
  176. ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
  177. return ajax;
  178. } catch (Exception e) {
  179. return AjaxResult.error(e.getMessage());
  180. }
  181. }
  182. /**
  183. * 本地资源通用下载
  184. */
  185. @GetMapping("/download/resource")
  186. public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
  187. throws Exception {
  188. try {
  189. if (!FileUtils.checkAllowDownload(resource)) {
  190. throw new Exception(StringUtils.format("资源文件({})非法,不允许下载。 ", resource));
  191. }
  192. // 本地资源路径
  193. String localPath = RuoYiConfig.getProfile();
  194. // 数据库资源地址
  195. String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
  196. // 下载名称
  197. String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
  198. response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
  199. FileUtils.setAttachmentResponseHeader(response, downloadName);
  200. FileUtils.writeBytes(downloadPath, response.getOutputStream());
  201. } catch (Exception e) {
  202. log.error("下载文件失败", e);
  203. }
  204. }
  205. /**
  206. * 生成二维码
  207. *
  208. * @param
  209. * @return
  210. */
  211. @GetMapping("/loginUserQRCode")
  212. public AjaxResult generateAndUploadQRCode() {
  213. String fileName = "";
  214. try {
  215. Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
  216. JSONObject userIdObj = new JSONObject();
  217. userIdObj.put("userId", userId);
  218. // 1. 生成临时二维码图片
  219. fileName = "qrcode_" + userId + ".png";
  220. Path tempFile = Paths.get(System.getProperty("java.io.tmpdir"), fileName);
  221. QRCodeUtils.generateQRCode(userIdObj.toJSONString(), tempFile, 300, 300);
  222. // 2. 转为 MultipartFile 格式,便于调用 RuoYi 的上传接口
  223. File file = tempFile.toFile();
  224. MultipartFile multipartFile = FileUtils.convertFileToMultipartFile(file);
  225. // 3. 使用 RuoYi 的文件上传工具进行上传
  226. String uploadPath = FileUploadUtils.upload(RuoYiConfig.getUploadPath(), multipartFile);
  227. // 4. 拼接访问 URL 并返回给前端
  228. String fileUrl = serverConfig.getUrl() + uploadPath;
  229. return AjaxResult.success("二维码生成成功", fileUrl);
  230. } catch (Exception e) {
  231. e.printStackTrace();
  232. return AjaxResult.error("二维码生成或上传失败");
  233. } finally {
  234. //清理临时文件
  235. FileUtils.cleanTempDir(fileName);
  236. }
  237. }
  238. }