PublicController.java 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. package com.goafanti.common.controller;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import java.util.ArrayList;
  9. import java.util.Date;
  10. import java.util.List;
  11. import java.util.UUID;
  12. import javax.annotation.Resource;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;
  15. import org.apache.commons.lang3.StringUtils;
  16. import org.apache.poi.ss.usermodel.Cell;
  17. import org.apache.poi.ss.usermodel.Row;
  18. import org.apache.poi.ss.usermodel.Sheet;
  19. import org.apache.poi.ss.usermodel.Workbook;
  20. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  21. import org.springframework.beans.factory.annotation.Autowired;
  22. import org.springframework.beans.factory.annotation.Value;
  23. import org.springframework.context.annotation.Scope;
  24. import org.springframework.http.MediaType;
  25. import org.springframework.stereotype.Controller;
  26. import org.springframework.web.bind.annotation.RequestMapping;
  27. import org.springframework.web.bind.annotation.RequestMethod;
  28. import org.springframework.web.bind.annotation.RequestParam;
  29. import org.springframework.web.bind.annotation.ResponseBody;
  30. import org.springframework.web.multipart.MultipartFile;
  31. import org.springframework.web.socket.TextMessage;
  32. import com.goafanti.admin.service.AdminService;
  33. import com.goafanti.admin.service.AttachmentService;
  34. import com.goafanti.common.bo.Error;
  35. import com.goafanti.common.bo.Result;
  36. import com.goafanti.common.constant.AFTConstants;
  37. import com.goafanti.common.constant.ErrorConstants;
  38. import com.goafanti.common.enums.UserType;
  39. import com.goafanti.common.model.User;
  40. import com.goafanti.common.service.DistrictGlossoryService;
  41. import com.goafanti.common.service.FieldGlossoryService;
  42. import com.goafanti.common.service.IndustryCategoryService;
  43. import com.goafanti.common.utils.DateUtils;
  44. import com.goafanti.common.utils.LoggerUtils;
  45. import com.goafanti.common.utils.MobileMessageUtils;
  46. import com.goafanti.common.utils.PasswordUtil;
  47. import com.goafanti.common.utils.PictureUtils;
  48. import com.goafanti.common.utils.TimeUtils;
  49. import com.goafanti.common.utils.VerifyCodeUtils;
  50. import com.goafanti.common.utils.excel.FileUtils;
  51. import com.goafanti.core.shiro.token.TokenManager;
  52. import com.goafanti.core.websocket.SystemWebSocketHandler;
  53. import com.goafanti.user.service.UserService;
  54. @Controller
  55. @Scope(value = "prototype")
  56. @RequestMapping("/open")
  57. public class PublicController extends CertifyApiController {
  58. @Value(value = "${accessKey}")
  59. private String accessKey = null;
  60. @Value(value = "${accessSecret}")
  61. private String accessSecret = null;
  62. @Value(value = "${upload.path}")
  63. private String uploadPath = null;
  64. @Value(value = "${upload.private.path}")
  65. private String uploadPrivatePath = null;
  66. @Value(value = "${static.host}")
  67. private String staticHost = null;
  68. @Value(value = "${mobileCodeTemplate}")
  69. private String mobileCodeTemplate = null;
  70. @Value(value = "${mobileRemindCodeTemplate}")
  71. private String mobileRemindCodeTemplate = null;
  72. @Resource
  73. private UserService userService;
  74. @Resource
  75. private AttachmentService aftFileService;
  76. @Resource
  77. private AdminService adminService;
  78. @Resource
  79. private FieldGlossoryService fieldGlossoryService;
  80. @Autowired
  81. private IndustryCategoryService industryCategoryService;
  82. @Autowired
  83. private DistrictGlossoryService districtGlossoryService;
  84. @Value(value = "${patentTemplate}")
  85. private String patentTemplate = null;
  86. @Resource(name = "passwordUtil")
  87. private PasswordUtil passwordUtil;
  88. /** 上传图片 **/
  89. @RequestMapping(value = "/upload", method = RequestMethod.POST)
  90. public Result uploadOrderInvoiceFile(HttpServletRequest req){
  91. Result res = new Result();
  92. res.setData(handleFile(res, "/publicRelease/", false, req, "publicRelease"));
  93. return res;
  94. }
  95. /**
  96. * 获取验证码
  97. *
  98. * @param response
  99. */
  100. @RequestMapping(value = "/getVCode", method = RequestMethod.GET)
  101. public void getVCode(HttpServletResponse response, HttpServletRequest request) {
  102. try {
  103. response.setHeader("Pragma", "No-cache");
  104. response.setHeader("Cache-Control", "no-cache");
  105. response.setDateHeader("Expires", 0);
  106. response.setContentType("image/jpg");
  107. // 生成随机字串
  108. String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
  109. // 存入Shiro会话session
  110. TokenManager.setVal2Session(VerifyCodeUtils.V_CODE, verifyCode.toLowerCase());
  111. // 生成图片
  112. int w = 146, h = 33;
  113. VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
  114. } catch (Exception e) {
  115. LoggerUtils.fmtError(getClass(), e, "获取验证码异常:%s", e.getMessage());
  116. }
  117. }
  118. /**
  119. * 手机验证码
  120. *
  121. * @param mobile
  122. * @param sign
  123. * 是否用与找回密码
  124. * @param type
  125. * @return
  126. */
  127. @RequestMapping(value = "/getMCode", method = RequestMethod.GET)
  128. @ResponseBody
  129. public Result getMcode(String mobile, boolean sign, Integer type, String verificationCode) {
  130. Result res = new Result();
  131. // 用于找回密码
  132. if (sign) {
  133. if (null == userService.selectByMobieAndType(mobile.trim(), type)) {
  134. res.getError().add(buildError(ErrorConstants.NON_REGISTER, "", "该用户未注册!"));
  135. return res;
  136. }
  137. }
  138. if (!sign) {
  139. if (StringUtils.isBlank(verificationCode)) {
  140. res.getError().add(buildError(ErrorConstants.VCODE_EMPTY_ERROR, "", "图像验证码不能为空!"));
  141. return res;
  142. }
  143. if (!VerifyCodeUtils.verifyCode(verificationCode)) {
  144. res.getError().add(buildError(ErrorConstants.VCODE_ERROR, "", "图形验证码输入错误!"));
  145. return res;
  146. }
  147. }
  148. if (TokenManager.getSession().getAttribute(VerifyCodeUtils.M_CODE_TIME) == null
  149. || TokenManager.getSession().getAttribute(VerifyCodeUtils.M_CODE_TIME) == "") {
  150. sendMessage(mobile, res,VerifyCodeUtils.M_CODE);
  151. } else if (TimeUtils.checkOverTime("getMCode")) {
  152. VerifyCodeUtils.clearMobileCode();
  153. VerifyCodeUtils.clearMobileCodeTime();
  154. sendMessage(mobile, res,VerifyCodeUtils.M_CODE);
  155. } else {
  156. res.getError().add(buildError(ErrorConstants.MCODE_FREQUENCY_ERROR, "", "手机验证码发送频繁!"));
  157. }
  158. return res;
  159. }
  160. /**
  161. *
  162. * @param mobile
  163. * @param res
  164. * @return
  165. */
  166. private Result sendMessage(String mobile, Result res,String codeType) {
  167. String mobileVerifyCode = VerifyCodeUtils.generateMobileVerifyCode(6); // 生成随机字串
  168. if(VerifyCodeUtils.M_CODE.equals(codeType)){
  169. TokenManager.setVal2Session(VerifyCodeUtils.M_CODE, mobileVerifyCode);// 存入Shiro会话session
  170. TokenManager.setVal2Session(VerifyCodeUtils.M_CODE_TIME, System.currentTimeMillis());
  171. }else if(VerifyCodeUtils.RESET_CODE.equals(codeType)){
  172. TokenManager.setVal2Session(VerifyCodeUtils.RESET_CODE, mobileVerifyCode);// 存入Shiro会话session
  173. TokenManager.setVal2Session(VerifyCodeUtils.RESET_CODE_TIME, System.currentTimeMillis());
  174. }
  175. String paramString = "{\"code\":\"" + mobileVerifyCode + "\",\"product\":\"技淘网\"}";
  176. String ret = MobileMessageUtils.sendMessage(mobileCodeTemplate, paramString, mobile, accessKey, accessSecret);
  177. if (StringUtils.isNotBlank(ret)) {
  178. res.getError().add(buildError(ErrorConstants.M_CODE_ERROR));
  179. }
  180. return res;
  181. }
  182. /**
  183. * 下载图片
  184. *
  185. * @param response
  186. * @param path
  187. * @param request
  188. */
  189. @RequestMapping(value = "/downLoadPicture", method = RequestMethod.GET)
  190. public Result downLoadPicture(HttpServletResponse response, String path, HttpServletRequest request) {
  191. Result res = new Result();
  192. if (StringUtils.isBlank(path)) {
  193. res.getError().add(buildError(ErrorConstants.FILE_NON_EXISTENT));
  194. return res;
  195. }
  196. String filename = Long.toString(System.nanoTime()) + ".jpg";
  197. InputStream in = null;
  198. OutputStream out = null;
  199. byte[] buffer = new byte[8 * 1024];
  200. String fileSaveRootPath = "";
  201. try {
  202. fileSaveRootPath = uploadPrivatePath + path;
  203. File file = new File(fileSaveRootPath);
  204. in = new FileInputStream(file);
  205. out = response.getOutputStream();
  206. // 设置文件MIME类型
  207. response.setContentType("application/octet-stream");
  208. response.setHeader("Content-Disposition", "attachment; filename=" + filename);
  209. for (;;) {
  210. int bytes = in.read(buffer);
  211. if (bytes == -1) {
  212. break;
  213. }
  214. out.write(buffer, 0, bytes);
  215. }
  216. } catch (IOException e) {
  217. LoggerUtils.fmtError(getClass(), e, "IO错误:%s", e.getMessage());
  218. } finally {
  219. try {
  220. if (null != in) {
  221. in.close();
  222. }
  223. } catch (IOException e) {
  224. LoggerUtils.fmtError(getClass(), e, "IO错误:%s", e.getMessage());
  225. }
  226. try {
  227. if (null != out) {
  228. out.close();
  229. }
  230. } catch (IOException e) {
  231. LoggerUtils.fmtError(getClass(), e, "IO错误:%s", e.getMessage());
  232. }
  233. }
  234. return res;
  235. }
  236. /**
  237. * 删除图片文件(public图片)
  238. *
  239. * @param path
  240. * @return
  241. */
  242. @RequestMapping(value = "/deleteUploadPicture", method = RequestMethod.POST)
  243. public boolean deleteUploadPicture(String path) {
  244. boolean flag = false;
  245. path = uploadPath + path;
  246. File file = new File(path);
  247. // 判断目录或文件是否存在
  248. if (!file.exists() || !file.isFile()) { // 不存在返回 false
  249. return flag;
  250. } else {
  251. return file.delete();
  252. }
  253. }
  254. /**
  255. * 获取并输出private图片
  256. */
  257. @RequestMapping(value = "/writeImage", method = RequestMethod.GET)
  258. public void writeImage(HttpServletResponse response, HttpServletRequest request, String path) {
  259. try {
  260. String realPath = uploadPrivatePath + path;
  261. PictureUtils.outputImage(response, realPath);
  262. } catch (IOException e) {
  263. LoggerUtils.fmtError(getClass(), e, "获取图片异常:%s", e.getMessage());
  264. }
  265. }
  266. /**
  267. * 下载文件
  268. *
  269. * @param res
  270. * @param fileName
  271. * @param response
  272. * @param path
  273. * @param request
  274. * @return
  275. */
  276. @RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
  277. public Result downloadFile(String fileName, HttpServletResponse response, String path) {
  278. Result res = new Result();
  279. return handleDownloadFile(response, fileName, path, res);
  280. }
  281. /**
  282. * 下载模版文件
  283. *
  284. * @param response
  285. * @return
  286. */
  287. @RequestMapping(value = "/downloadTemplateFile", method = RequestMethod.GET)
  288. public Result downloadTemplateFile(HttpServletResponse response, String sign) {
  289. Result res = new Result();
  290. String fileName = "";
  291. String path = aftFileService.selectAftFileBySign(sign).getFilePath();
  292. String suffix = path.substring(path.lastIndexOf("."));
  293. if (sign.equals("patent_prory_statement")) {
  294. fileName = "专利代理委托书模版" + suffix;
  295. } else {
  296. fileName = System.nanoTime() + " ";
  297. }
  298. if (!StringUtils.isBlank(path)) {
  299. return handleDownloadFile(response, fileName, path, res);
  300. } else {
  301. res.getError().add(buildError(ErrorConstants.FILE_NON_EXISTENT, "", "下载文件不存在!"));
  302. return res;
  303. }
  304. }
  305. private Result handleDownloadFile(HttpServletResponse response, String fileName, String path, Result res) {
  306. String fileSaveRootPath = uploadPrivatePath + path;
  307. InputStream in = null;
  308. OutputStream out = null;
  309. byte[] buffer = new byte[8 * 1024];
  310. try {
  311. File file = new File(fileSaveRootPath);
  312. in = new FileInputStream(file);
  313. out = response.getOutputStream();
  314. response.setContentType("multipart/form-data");
  315. fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
  316. response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
  317. for (;;) {
  318. int bytes = in.read(buffer);
  319. if (bytes == -1) {
  320. break;
  321. }
  322. out.write(buffer, 0, bytes);
  323. }
  324. } catch (IOException e) {
  325. LoggerUtils.fmtError(getClass(), e, "IO错误:%s", e.getMessage());
  326. } finally {
  327. try {
  328. in.close();
  329. } catch (IOException e) {
  330. LoggerUtils.fmtError(getClass(), e, "IO错误:%s", e.getMessage());
  331. }
  332. try {
  333. out.close();
  334. } catch (IOException e) {
  335. LoggerUtils.fmtError(getClass(), e, "IO错误:%s", e.getMessage());
  336. }
  337. }
  338. return res;
  339. }
  340. @RequestMapping(value = "/findIndustryCategory", method = RequestMethod.GET)
  341. @ResponseBody
  342. public Result findIndustryCategory(String id, String noCache) {
  343. Integer pid = 0;
  344. if (StringUtils.isNumeric(id)) {
  345. try {
  346. pid = Integer.parseInt(id);
  347. } catch (Exception e) {
  348. pid = 0;
  349. }
  350. }
  351. if (StringUtils.isNotBlank(noCache)) {
  352. industryCategoryService.clear(pid);
  353. }
  354. return new Result().data(industryCategoryService.list(pid));
  355. }
  356. @RequestMapping(value = "/findDistrict", method = RequestMethod.GET)
  357. @ResponseBody
  358. public Result findDistrictGlossory(String id, String noCache) {
  359. Integer pid = 0;
  360. if (StringUtils.isNumeric(id)) {
  361. try {
  362. pid = Integer.parseInt(id);
  363. } catch (Exception e) {
  364. pid = 0;
  365. }
  366. }
  367. if (StringUtils.isNotBlank(noCache)) {
  368. districtGlossoryService.clear(pid);
  369. }
  370. return new Result().data(districtGlossoryService.list(pid));
  371. }
  372. /**
  373. *
  374. * @param mobileCode
  375. * @return
  376. */
  377. @RequestMapping(value = "/checkMCode", method = RequestMethod.POST)
  378. @ResponseBody
  379. public Result checkMCode(String mobileCode) {
  380. Result res = new Result();
  381. if (StringUtils.isBlank(mobileCode)) {
  382. res.getError().add(buildError(ErrorConstants.MCODE_EMPTY_ERROR, "", "手机验证码"));
  383. return res;
  384. }
  385. if (TimeUtils.checkOverTime(VerifyCodeUtils.M_CODE)) {
  386. res.getError().add(buildError(ErrorConstants.MCODE_OVERTIME_ERROR, "", "手机验证码超时失效!"));
  387. VerifyCodeUtils.clearMobileCode();
  388. VerifyCodeUtils.clearMobileCodeTime();
  389. return res;
  390. }
  391. if (!TokenManager.getSession().getAttribute(VerifyCodeUtils.M_CODE).equals(mobileCode)) {
  392. res.getError().add(buildError(ErrorConstants.MCODE_ERROR, "", "手机验证码错误"));
  393. return res;
  394. }
  395. // resetCode
  396. if (res.getError().isEmpty()) {
  397. String resetCode = UUID.randomUUID().toString();
  398. TokenManager.setVal2Session(VerifyCodeUtils.RESET_CODE, resetCode);
  399. TokenManager.setVal2Session(VerifyCodeUtils.RESET_CODE_TIME, System.currentTimeMillis());
  400. res.setData(resetCode);
  401. }
  402. return res;
  403. }
  404. /**
  405. * 重置密码
  406. *
  407. * @param resetCode
  408. * @param mobile
  409. * @param type
  410. * @param newPwd
  411. * @return
  412. */
  413. @RequestMapping(value = "/resetPwd", method = RequestMethod.POST)
  414. @ResponseBody
  415. public Result resetPwd(String resetCode, String mobile, Integer type, String newPwd) {
  416. Result res = new Result();
  417. if (TimeUtils.checkOverTime(VerifyCodeUtils.M_CODE)) {
  418. res.getError().add(buildError(ErrorConstants.RESET_CODE_OVERTIME, "", "页面超时失效,请重新获取验证码!"));
  419. cleanCodeSession();
  420. return res;
  421. }
  422. if(null == TokenManager.getSession().getAttribute(VerifyCodeUtils.RESET_CODE)){
  423. res.getError().add(buildError(ErrorConstants.RESET_CODE_OVERTIME, "", "页面超时失效,请重新获取验证码!"));
  424. cleanCodeSession();
  425. return res;
  426. }else if(!TokenManager.getSession().getAttribute(VerifyCodeUtils.RESET_CODE).equals(resetCode)){
  427. res.getError().add(buildError(ErrorConstants.RESET_CODE_ERROR, "", "验证码错误,请重新获取验证码!"));
  428. cleanCodeSession();
  429. return res;
  430. }
  431. if (StringUtils.isBlank(newPwd)) {
  432. res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "新密码"));
  433. return res;
  434. }
  435. if (StringUtils.isBlank(mobile)) {
  436. res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "mobile"));
  437. return res;
  438. }
  439. if (!UserType.ORGANIZATION.getCode().equals(type) && !UserType.PERSONAL.getCode().equals(type)) {
  440. res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "type"));
  441. return res;
  442. }
  443. User user = userService.selectByMobieAndType(mobile, type);
  444. if (null == user) {
  445. res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "mobile"));
  446. return res;
  447. }
  448. user.setPassword(newPwd);
  449. user.setPassword(passwordUtil.getEncryptPwd(user));
  450. userService.updateByPrimaryKeySelective(user);
  451. VerifyCodeUtils.clearResetCode();
  452. VerifyCodeUtils.clearResetCodeTime();
  453. return res;
  454. }
  455. private void cleanCodeSession() {
  456. VerifyCodeUtils.clearResetCode();
  457. VerifyCodeUtils.clearResetCodeTime();
  458. VerifyCodeUtils.clearMobileCode();
  459. VerifyCodeUtils.clearMobileCodeTime();
  460. }
  461. @RequestMapping(value = "/getRegisterMCode", method = RequestMethod.GET )
  462. @ResponseBody
  463. public Result getRegisterMCode(String mobile){
  464. Result res = new Result();
  465. if (TokenManager.getSession().getAttribute(VerifyCodeUtils.M_CODE_TIME) == null
  466. || TokenManager.getSession().getAttribute(VerifyCodeUtils.M_CODE_TIME) == "") {
  467. sendMessage(mobile, res,VerifyCodeUtils.M_CODE);
  468. } else if (TimeUtils.checkOverTime("getMCode")) {
  469. VerifyCodeUtils.clearMobileCode();
  470. VerifyCodeUtils.clearMobileCodeTime();
  471. sendMessage(mobile, res,VerifyCodeUtils.M_CODE);
  472. } else {
  473. res.getError().add(buildError(ErrorConstants.MCODE_FREQUENCY_ERROR, "", "手机验证码发送频繁!"));
  474. }
  475. return res;
  476. }
  477. @RequestMapping(value = "/getResetMCode", method = RequestMethod.GET )
  478. @ResponseBody
  479. public Result getResetMCode(String mobile, Integer type) {
  480. Result res = new Result();
  481. if (null == userService.selectByMobieAndType(mobile.trim(), type)) {
  482. res.getError().add(buildError(ErrorConstants.NON_REGISTER, "", "该用户未注册!"));
  483. return res;
  484. }
  485. if (TokenManager.getSession().getAttribute(VerifyCodeUtils.RESET_CODE_TIME) == null
  486. || TokenManager.getSession().getAttribute(VerifyCodeUtils.RESET_CODE_TIME) == "") {
  487. sendMessage(mobile, res,VerifyCodeUtils.RESET_CODE);
  488. } else if (TimeUtils.checkOverTime("resetCode")) {
  489. VerifyCodeUtils.clearMobileCode();
  490. VerifyCodeUtils.clearMobileCodeTime();
  491. sendMessage(mobile, res,VerifyCodeUtils.RESET_CODE);
  492. } else {
  493. res.getError().add(buildError(ErrorConstants.MCODE_FREQUENCY_ERROR, "", "手机验证码发送频繁!"));
  494. }
  495. return res;
  496. }
  497. /** 省市区查询 **/
  498. @RequestMapping(value = "/listAllProvince" , method = RequestMethod.POST)
  499. @ResponseBody
  500. public Result listAllProvince(){
  501. Result res = new Result();
  502. res.setData(districtGlossoryService.getProvince());
  503. return res;
  504. }
  505. @RequestMapping(value = "/listDefaultPassword" , method = RequestMethod.GET)
  506. @ResponseBody
  507. public Result listDefaultPassword(String depId){
  508. Result res=new Result();
  509. res.setData(adminService.getListDefaultPassword(depId));
  510. return res;
  511. }
  512. /** 省市区查询 **/
  513. @RequestMapping(value = "/sendWeb" , method = RequestMethod.POST)
  514. @ResponseBody
  515. public Result sendWeb(String str){
  516. Result res = new Result();
  517. SystemWebSocketHandler sys=new SystemWebSocketHandler();
  518. TextMessage text=new TextMessage(str.getBytes());
  519. sys.sendMessageToUsers(text);
  520. res.setData(1);
  521. return res;
  522. }
  523. /**
  524. * 导入流水
  525. * @param file
  526. * @param request
  527. * @return
  528. */
  529. @SuppressWarnings("unchecked")
  530. @RequestMapping(value = "/import" , method = RequestMethod.POST)
  531. @ResponseBody
  532. public Result importTeacher(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
  533. Result res=new Result();
  534. String fileName = file.getOriginalFilename();
  535. if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
  536. res.error(new Error("", "格式不正确"));
  537. }
  538. //检查文件
  539. try {
  540. checkFile(file);
  541. } catch (IOException e) {
  542. e.printStackTrace();
  543. }
  544. //获得Workbook工作薄对象
  545. Workbook workbook = getWorkBook(file);
  546. //创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回
  547. List<List<String>> list = new ArrayList<>();
  548. if(workbook != null){
  549. for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){
  550. //获得当前sheet工作表
  551. Sheet sheet = workbook.getSheetAt(sheetNum);
  552. if(sheet == null){
  553. continue;
  554. }
  555. //获得当前sheet的开始行
  556. int firstRowNum = sheet.getFirstRowNum();
  557. //获得当前sheet的结束行
  558. int lastRowNum = sheet.getLastRowNum();
  559. //循环除了第2行的所有行
  560. for(int rowNum = firstRowNum+2;rowNum <= lastRowNum;rowNum++){
  561. //获得当前行
  562. Row row = sheet.getRow(rowNum);
  563. if(row == null){
  564. continue;
  565. }
  566. //获得当前行的开始列
  567. int firstCellNum = row.getFirstCellNum();
  568. //获得当前行的列数
  569. int lastCellNum = row.getLastCellNum();
  570. @SuppressWarnings("rawtypes")
  571. ArrayList arrayList = new ArrayList();
  572. //循环当前行 cellNum = (firstCellNum+1) 则是除开第一例
  573. for(int cellNum = (firstCellNum); cellNum < lastCellNum;cellNum++){
  574. Cell cell = row.getCell(cellNum);
  575. arrayList.add(getCellValue(cell));
  576. }
  577. list.add(arrayList);
  578. }
  579. }
  580. }
  581. return res;
  582. }
  583. public static void checkFile(MultipartFile file) throws IOException{
  584. //判断文件是否存在
  585. if(null == file){
  586. throw new FileNotFoundException("文件不存在!");
  587. }
  588. //获得文件名
  589. String fileName = file.getOriginalFilename();
  590. //判断文件是否是excel文件
  591. if(!fileName.endsWith("xls") && !fileName.endsWith("xlsx")){
  592. throw new IOException(fileName + "不是excel文件");
  593. }
  594. }
  595. public static Workbook getWorkBook(MultipartFile file) {
  596. //创建Workbook工作薄对象,表示整个excel
  597. Workbook workbook = null;
  598. try {
  599. //获取excel文件的io流
  600. InputStream is = file.getInputStream();
  601. //如果是xls,使用HSSFWorkbook;如果是xlsx,使用XSSFWorkbook
  602. workbook = new XSSFWorkbook(is);
  603. } catch (IOException e) {
  604. }
  605. return workbook;
  606. }
  607. @SuppressWarnings("deprecation")
  608. public static String getCellValue(Cell cell){
  609. String cellValue = "";
  610. if(cell == null){
  611. return cellValue;
  612. }
  613. //把数字当成String来读,避免出现1读成1.0的情况
  614. if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
  615. cell.setCellType(Cell.CELL_TYPE_STRING);
  616. }
  617. //判断数据的类型
  618. switch (cell.getCellType()){
  619. case Cell.CELL_TYPE_NUMERIC: //数字
  620. cellValue = String.valueOf(cell.getNumericCellValue());
  621. break;
  622. case Cell.CELL_TYPE_STRING: //字符串
  623. cellValue = String.valueOf(cell.getStringCellValue());
  624. break;
  625. case Cell.CELL_TYPE_BOOLEAN: //Boolean
  626. cellValue = String.valueOf(cell.getBooleanCellValue());
  627. break;
  628. case Cell.CELL_TYPE_FORMULA: //公式
  629. cellValue = String.valueOf(cell.getCellFormula());
  630. break;
  631. case Cell.CELL_TYPE_BLANK: //空值
  632. cellValue = "未知";
  633. break;
  634. case Cell.CELL_TYPE_ERROR: //故障
  635. cellValue = "非法字符";
  636. break;
  637. default:
  638. cellValue = "未知类型";
  639. break;
  640. }
  641. return cellValue;
  642. }
  643. /**
  644. * 通用下载请求
  645. *
  646. * @param fileName 文件名称
  647. * @param delete 是否删除
  648. */
  649. @RequestMapping("/download")
  650. public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
  651. {
  652. try
  653. {
  654. if (!FileUtils.checkAllowDownload(fileName))
  655. {
  656. throw new Exception("文件名称({})非法,不允许下载。 ");
  657. }
  658. String realFileName =DateUtils.parseDateToStr(AFTConstants.YYYYMMDDHHMMSS, new Date())+fileName.substring(fileName.indexOf("_") + 1);
  659. String filePath = uploadPath +"/"+ fileName;
  660. response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
  661. FileUtils.setAttachmentResponseHeader(response, realFileName);
  662. FileUtils.writeBytes(filePath, response.getOutputStream());
  663. if (delete)
  664. {
  665. FileUtils.deleteFile(filePath);
  666. }
  667. }
  668. catch (Exception e)
  669. {
  670. LoggerUtils.error(PublicController.class,"下载文件失败", e);
  671. }
  672. }
  673. }