2cea6488822055967d1b083bf32aad51aa1ecc56.svn-base 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. package org.jeecg.modules.system.controller;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.apache.xmlbeans.impl.xb.xsdschema.Public;
  6. import org.jeecg.common.api.vo.Result;
  7. import org.jeecg.common.constant.CommonConstant;
  8. import org.jeecg.common.system.api.ISysBaseAPI;
  9. import org.jeecg.common.util.CommonUtils;
  10. import org.jeecg.common.util.RestUtil;
  11. import org.jeecg.common.util.TokenUtils;
  12. import org.jeecg.common.util.oConvertUtils;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.beans.factory.annotation.Value;
  15. import org.springframework.http.HttpHeaders;
  16. import org.springframework.http.HttpMethod;
  17. import org.springframework.http.ResponseEntity;
  18. import org.springframework.http.server.ServletServerHttpRequest;
  19. import org.springframework.util.AntPathMatcher;
  20. import org.springframework.util.FileCopyUtils;
  21. import org.springframework.web.bind.annotation.*;
  22. import org.springframework.web.multipart.MultipartFile;
  23. import org.springframework.web.multipart.MultipartHttpServletRequest;
  24. import org.springframework.web.servlet.HandlerMapping;
  25. import org.springframework.web.servlet.ModelAndView;
  26. import javax.servlet.http.HttpServletRequest;
  27. import javax.servlet.http.HttpServletResponse;
  28. import java.io.*;
  29. import java.net.URLDecoder;
  30. /**
  31. * <p>
  32. * 用户表 前端控制器
  33. * </p>
  34. *
  35. * @Author scott
  36. * @since 2018-12-20
  37. */
  38. @Slf4j
  39. @RestController
  40. @RequestMapping("/sys/common")
  41. public class CommonController {
  42. @Autowired
  43. private ISysBaseAPI sysBaseAPI;
  44. @Value(value = "${jeecg.path.upload}")
  45. private String uploadpath;
  46. /**
  47. * 本地:local minio:minio 阿里:alioss
  48. */
  49. @Value(value="${jeecg.uploadType}")
  50. private String uploadType;
  51. /**
  52. * @Author 政辉
  53. * @return
  54. */
  55. @GetMapping("/403")
  56. public Result<?> noauth() {
  57. return Result.error("没有权限,请联系管理员授权");
  58. }
  59. /**
  60. * 文件上传统一方法
  61. * @param request
  62. * @param response
  63. * @return
  64. */
  65. @PostMapping(value = "/upload")
  66. public Result<?> upload(HttpServletRequest request, HttpServletResponse response) {
  67. Result<?> result = new Result<>();
  68. String savePath = "";
  69. String bizPath = request.getParameter("biz");
  70. MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  71. MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
  72. if(oConvertUtils.isEmpty(bizPath)){
  73. if(CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)){
  74. //未指定目录,则用阿里云默认目录 upload
  75. bizPath = "upload";
  76. //result.setMessage("使用阿里云文件上传时,必须添加目录!");
  77. //result.setSuccess(false);
  78. //return result;
  79. }else{
  80. bizPath = "";
  81. }
  82. }
  83. if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){
  84. //update-begin-author:lvdandan date:20200928 for:修改JEditor编辑器本地上传
  85. savePath = this.uploadLocal(file,bizPath);
  86. //update-begin-author:lvdandan date:20200928 for:修改JEditor编辑器本地上传
  87. /** 富文本编辑器及markdown本地上传时,采用返回链接方式
  88. //针对jeditor编辑器如何使 lcaol模式,采用 base64格式存储
  89. String jeditor = request.getParameter("jeditor");
  90. if(oConvertUtils.isNotEmpty(jeditor)){
  91. result.setMessage(CommonConstant.UPLOAD_TYPE_LOCAL);
  92. result.setSuccess(true);
  93. return result;
  94. }else{
  95. savePath = this.uploadLocal(file,bizPath);
  96. }
  97. */
  98. }else{
  99. //update-begin-author:taoyan date:20200814 for:文件上传改造
  100. savePath = CommonUtils.upload(file, bizPath, uploadType);
  101. //update-end-author:taoyan date:20200814 for:文件上传改造
  102. }
  103. if(oConvertUtils.isNotEmpty(savePath)){
  104. result.setMessage(savePath);
  105. result.setSuccess(true);
  106. }else {
  107. result.setMessage("上传失败!");
  108. result.setSuccess(false);
  109. }
  110. return result;
  111. }
  112. /**
  113. * 本地文件上传
  114. * @param mf 文件
  115. * @param bizPath 自定义路径
  116. * @return
  117. */
  118. private String uploadLocal(MultipartFile mf,String bizPath){
  119. try {
  120. String ctxPath = uploadpath;
  121. String fileName = null;
  122. File file = new File(ctxPath + File.separator + bizPath + File.separator );
  123. if (!file.exists()) {
  124. file.mkdirs();// 创建文件根目录
  125. }
  126. String orgName = mf.getOriginalFilename();// 获取文件名
  127. orgName = CommonUtils.getFileName(orgName);
  128. if(orgName.indexOf(".")!=-1){
  129. fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
  130. }else{
  131. fileName = orgName+ "_" + System.currentTimeMillis();
  132. }
  133. String savePath = file.getPath() + File.separator + fileName;
  134. File savefile = new File(savePath);
  135. FileCopyUtils.copy(mf.getBytes(), savefile);
  136. String dbpath = null;
  137. if(oConvertUtils.isNotEmpty(bizPath)){
  138. dbpath = bizPath + File.separator + fileName;
  139. }else{
  140. dbpath = fileName;
  141. }
  142. if (dbpath.contains("\\")) {
  143. dbpath = dbpath.replace("\\", "/");
  144. }
  145. return dbpath;
  146. } catch (IOException e) {
  147. log.error(e.getMessage(), e);
  148. }
  149. return "";
  150. }
  151. // @PostMapping(value = "/upload2")
  152. // public Result<?> upload2(HttpServletRequest request, HttpServletResponse response) {
  153. // Result<?> result = new Result<>();
  154. // try {
  155. // String ctxPath = uploadpath;
  156. // String fileName = null;
  157. // String bizPath = "files";
  158. // String tempBizPath = request.getParameter("biz");
  159. // if(oConvertUtils.isNotEmpty(tempBizPath)){
  160. // bizPath = tempBizPath;
  161. // }
  162. // String nowday = new SimpleDateFormat("yyyyMMdd").format(new Date());
  163. // File file = new File(ctxPath + File.separator + bizPath + File.separator + nowday);
  164. // if (!file.exists()) {
  165. // file.mkdirs();// 创建文件根目录
  166. // }
  167. // MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  168. // MultipartFile mf = multipartRequest.getFile("file");// 获取上传文件对象
  169. // String orgName = mf.getOriginalFilename();// 获取文件名
  170. // fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
  171. // String savePath = file.getPath() + File.separator + fileName;
  172. // File savefile = new File(savePath);
  173. // FileCopyUtils.copy(mf.getBytes(), savefile);
  174. // String dbpath = bizPath + File.separator + nowday + File.separator + fileName;
  175. // if (dbpath.contains("\\")) {
  176. // dbpath = dbpath.replace("\\", "/");
  177. // }
  178. // result.setMessage(dbpath);
  179. // result.setSuccess(true);
  180. // } catch (IOException e) {
  181. // result.setSuccess(false);
  182. // result.setMessage(e.getMessage());
  183. // log.error(e.getMessage(), e);
  184. // }
  185. // return result;
  186. // }
  187. /**
  188. * 预览图片&下载文件
  189. * 请求地址:http://localhost:8080/common/static/{user/20190119/e1fe9925bc315c60addea1b98eb1cb1349547719_1547866868179.jpg}
  190. *
  191. * @param request
  192. * @param response
  193. */
  194. @GetMapping(value = "/static/**")
  195. public void view(HttpServletRequest request, HttpServletResponse response) {
  196. // ISO-8859-1 ==> UTF-8 进行编码转换
  197. String imgPath = extractPathFromPattern(request);
  198. if(oConvertUtils.isEmpty(imgPath) || imgPath=="null"){
  199. return;
  200. }
  201. // 其余处理略
  202. InputStream inputStream = null;
  203. OutputStream outputStream = null;
  204. try {
  205. imgPath = imgPath.replace("..", "").replace("../","");
  206. if (imgPath.endsWith(",")) {
  207. imgPath = imgPath.substring(0, imgPath.length() - 1);
  208. }
  209. String filePath = uploadpath + File.separator + imgPath;
  210. File file = new File(filePath);
  211. if(!file.exists()){
  212. response.setStatus(404);
  213. throw new RuntimeException("文件["+imgPath+"]不存在..");
  214. }
  215. response.setContentType("application/force-download");// 设置强制下载不打开
  216. response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));
  217. inputStream = new BufferedInputStream(new FileInputStream(filePath));
  218. outputStream = response.getOutputStream();
  219. byte[] buf = new byte[1024];
  220. int len;
  221. while ((len = inputStream.read(buf)) > 0) {
  222. outputStream.write(buf, 0, len);
  223. }
  224. response.flushBuffer();
  225. } catch (IOException e) {
  226. log.error("预览文件失败" + e.getMessage());
  227. response.setStatus(404);
  228. e.printStackTrace();
  229. } finally {
  230. if (inputStream != null) {
  231. try {
  232. inputStream.close();
  233. } catch (IOException e) {
  234. log.error(e.getMessage(), e);
  235. }
  236. }
  237. if (outputStream != null) {
  238. try {
  239. outputStream.close();
  240. } catch (IOException e) {
  241. log.error(e.getMessage(), e);
  242. }
  243. }
  244. }
  245. }
  246. // /**
  247. // * 下载文件
  248. // * 请求地址:http://localhost:8080/common/download/{user/20190119/e1fe9925bc315c60addea1b98eb1cb1349547719_1547866868179.jpg}
  249. // *
  250. // * @param request
  251. // * @param response
  252. // * @throws Exception
  253. // */
  254. // @GetMapping(value = "/download/**")
  255. // public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
  256. // // ISO-8859-1 ==> UTF-8 进行编码转换
  257. // String filePath = extractPathFromPattern(request);
  258. // // 其余处理略
  259. // InputStream inputStream = null;
  260. // OutputStream outputStream = null;
  261. // try {
  262. // filePath = filePath.replace("..", "");
  263. // if (filePath.endsWith(",")) {
  264. // filePath = filePath.substring(0, filePath.length() - 1);
  265. // }
  266. // String localPath = uploadpath;
  267. // String downloadFilePath = localPath + File.separator + filePath;
  268. // File file = new File(downloadFilePath);
  269. // if (file.exists()) {
  270. // response.setContentType("application/force-download");// 设置强制下载不打开            
  271. // response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));
  272. // inputStream = new BufferedInputStream(new FileInputStream(file));
  273. // outputStream = response.getOutputStream();
  274. // byte[] buf = new byte[1024];
  275. // int len;
  276. // while ((len = inputStream.read(buf)) > 0) {
  277. // outputStream.write(buf, 0, len);
  278. // }
  279. // response.flushBuffer();
  280. // }
  281. //
  282. // } catch (Exception e) {
  283. // log.info("文件下载失败" + e.getMessage());
  284. // // e.printStackTrace();
  285. // } finally {
  286. // if (inputStream != null) {
  287. // try {
  288. // inputStream.close();
  289. // } catch (IOException e) {
  290. // e.printStackTrace();
  291. // }
  292. // }
  293. // if (outputStream != null) {
  294. // try {
  295. // outputStream.close();
  296. // } catch (IOException e) {
  297. // e.printStackTrace();
  298. // }
  299. // }
  300. // }
  301. //
  302. // }
  303. /**
  304. * @功能:pdf预览Iframe
  305. * @param modelAndView
  306. * @return
  307. */
  308. @RequestMapping("/pdf/pdfPreviewIframe")
  309. public ModelAndView pdfPreviewIframe(ModelAndView modelAndView) {
  310. modelAndView.setViewName("pdfPreviewIframe");
  311. return modelAndView;
  312. }
  313. /**
  314. * 把指定URL后的字符串全部截断当成参数
  315. * 这么做是为了防止URL中包含中文或者特殊字符(/等)时,匹配不了的问题
  316. * @param request
  317. * @return
  318. */
  319. private static String extractPathFromPattern(final HttpServletRequest request) {
  320. String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
  321. String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
  322. return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
  323. }
  324. /**
  325. * 中转HTTP请求,解决跨域问题
  326. *
  327. * @param url 必填:请求地址
  328. * @return
  329. */
  330. @RequestMapping("/transitRESTful")
  331. public Result transitRESTful(@RequestParam("url") String url, HttpServletRequest request) {
  332. try {
  333. ServletServerHttpRequest httpRequest = new ServletServerHttpRequest(request);
  334. // 中转请求method、body
  335. HttpMethod method = httpRequest.getMethod();
  336. JSONObject params;
  337. try {
  338. params = JSON.parseObject(JSON.toJSONString(httpRequest.getBody()));
  339. } catch (Exception e) {
  340. params = new JSONObject();
  341. }
  342. // 中转请求问号参数
  343. JSONObject variables = JSON.parseObject(JSON.toJSONString(request.getParameterMap()));
  344. variables.remove("url");
  345. // 在 headers 里传递Token
  346. String token = TokenUtils.getTokenByRequest(request);
  347. HttpHeaders headers = new HttpHeaders();
  348. headers.set("X-Access-Token", token);
  349. // 发送请求
  350. String httpURL = URLDecoder.decode(url, "UTF-8");
  351. ResponseEntity<String> response = RestUtil.request(httpURL, method, headers , variables, params, String.class);
  352. // 封装返回结果
  353. Result<Object> result = new Result<>();
  354. int statusCode = response.getStatusCodeValue();
  355. result.setCode(statusCode);
  356. result.setSuccess(statusCode == 200);
  357. String responseBody = response.getBody();
  358. try {
  359. // 尝试将返回结果转为JSON
  360. Object json = JSON.parse(responseBody);
  361. result.setResult(json);
  362. } catch (Exception e) {
  363. // 转成JSON失败,直接返回原始数据
  364. result.setResult(responseBody);
  365. }
  366. return result;
  367. } catch (Exception e) {
  368. log.debug("中转HTTP请求失败", e);
  369. return Result.error(e.getMessage());
  370. }
  371. }
  372. }