CommonController.java 12 KB

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