LocalSysFileServiceImpl.java 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  1. package com.xunmei.file.service;
  2. import cn.hutool.core.collection.CollectionUtil;
  3. import cn.hutool.core.date.DateUtil;
  4. import cn.hutool.core.io.FileUtil;
  5. import cn.hutool.core.util.ArrayUtil;
  6. import cn.hutool.core.util.ObjectUtil;
  7. import com.alibaba.fastjson2.JSON;
  8. import com.baomidou.mybatisplus.core.toolkit.IdWorker;
  9. import com.lowagie.text.*;
  10. import com.lowagie.text.pdf.BaseFont;
  11. import com.lowagie.text.pdf.PdfPCell;
  12. import com.lowagie.text.pdf.PdfPTable;
  13. import com.lowagie.text.pdf.PdfWriter;
  14. import com.xunmei.common.core.constant.CacheConstants;
  15. import com.xunmei.common.core.domain.IdName;
  16. import com.xunmei.common.core.domain.registerbook.dto.CoreRegisterBookPdfExportDto;
  17. import com.xunmei.common.core.domain.registerbook.dto.ExportPdfDto;
  18. import com.xunmei.common.core.domain.registerbook.vo.CoreRegisterBookPdfPageVo;
  19. import com.xunmei.common.core.domain.registerbook.vo.PdfLocalFileTempVo;
  20. import com.xunmei.common.core.domain.registerbook.vo.PdfToZipTempVo;
  21. import com.xunmei.common.core.enums.RegisterBookType;
  22. import com.xunmei.common.core.utils.DateHelper;
  23. import com.xunmei.common.core.utils.uuid.UUID;
  24. import com.xunmei.common.redis.utils.RedisUtils;
  25. import com.xunmei.file.utils.FileDownUtils;
  26. import com.xunmei.file.utils.FileUploadUtils;
  27. import com.xunmei.file.utils.PdfUtil;
  28. import com.xunmei.file.vo.FileBase64Vo;
  29. import com.xunmei.file.vo.ItextPdfTableVo;
  30. import com.xunmei.file.vo.PdfFilePathVo;
  31. import com.xunmei.system.api.domain.AccessPdf;
  32. import com.xunmei.system.api.domain.SafeCheckTaskRegisterBookVo;
  33. import com.xunmei.system.api.vo.SysOrgVO;
  34. import io.netty.util.internal.StringUtil;
  35. import org.apache.commons.io.FileUtils;
  36. import org.apache.commons.lang3.StringUtils;
  37. import org.apache.commons.text.StringEscapeUtils;
  38. import org.apache.tools.zip.ZipEntry;
  39. import org.apache.tools.zip.ZipOutputStream;
  40. import org.slf4j.Logger;
  41. import org.slf4j.LoggerFactory;
  42. import org.springframework.beans.factory.annotation.Autowired;
  43. import org.springframework.beans.factory.annotation.Value;
  44. import org.springframework.context.annotation.Primary;
  45. import org.springframework.data.redis.core.BoundValueOperations;
  46. import org.springframework.data.redis.core.StringRedisTemplate;
  47. import org.springframework.stereotype.Service;
  48. import org.springframework.web.multipart.MultipartFile;
  49. import javax.servlet.ServletOutputStream;
  50. import javax.servlet.http.HttpServletRequest;
  51. import javax.servlet.http.HttpServletResponse;
  52. import java.io.*;
  53. import java.math.BigDecimal;
  54. import java.net.HttpURLConnection;
  55. import java.net.URL;
  56. import java.net.URLDecoder;
  57. import java.net.URLEncoder;
  58. import java.nio.charset.StandardCharsets;
  59. import java.nio.file.Files;
  60. import java.nio.file.Paths;
  61. import java.util.List;
  62. import java.util.*;
  63. import java.util.concurrent.CountDownLatch;
  64. import java.util.regex.Matcher;
  65. import java.util.regex.Pattern;
  66. import java.util.stream.Collectors;
  67. import static com.xunmei.file.utils.PdfUtil.dealImageCell;
  68. import static java.util.regex.Pattern.compile;
  69. /**
  70. * 本地文件存储
  71. *
  72. * @author xunmei
  73. */
  74. @Primary
  75. @Service
  76. public class LocalSysFileServiceImpl implements ISysFileService {
  77. private static final Logger log = LoggerFactory.getLogger(LocalSysFileServiceImpl.class);
  78. public static final String TEMP_DIR_NAME = "registerBookPdfBatchExportTempDir";
  79. @Value("${file.path}")
  80. private String localFilePath;
  81. @Value("${file.prefix}")
  82. public String prefix;
  83. @Autowired
  84. private HttpServletRequest request;
  85. @Autowired
  86. private StringRedisTemplate redisTemplate;
  87. private PdfFilePathVo getLocalFilePath(String businessType, String fileName) {
  88. // 验证输入
  89. if (isValidFileName(fileName)) {
  90. throw new IllegalArgumentException("Invalid file name");
  91. }
  92. final String path = File.separator + businessType +
  93. File.separator +
  94. DateUtil.format(new Date(), "yyyy" + File.separator + "MM" + File.separator + "dd" +
  95. File.separator);
  96. String filePath = localFilePath + path;
  97. // 规范化路径
  98. String absolutePath = Paths.get(filePath).toAbsolutePath().normalize().toString();
  99. final File file = FileUtils.getFile(absolutePath);
  100. if (!file.exists()) {
  101. file.mkdirs();
  102. }
  103. PdfFilePathVo pathVo = new PdfFilePathVo();
  104. pathVo.setAbsolutePath(localFilePath + path + fileName);
  105. pathVo.setTempFileName(localFilePath + path + IdWorker.getId() + ".pdf");
  106. pathVo.setRelativePath(path + fileName);
  107. return pathVo;
  108. }
  109. private boolean isValidFileName(String fileName) {
  110. /*
  111. a-zA-Z:匹配所有大写和小写字母;
  112. 0-9:匹配所有数字;
  113. ._\-:匹配点(.)、下划线(_)和短横线(-)。
  114. +:表示前面的字符集出现一次或多次。
  115. */
  116. // 使用正则表达式检查文件名是否合法
  117. //return fileName.matches("[a-zA-Z0-9._\\-]+");
  118. return fileName.matches("[a-zA-Z0-9]+");
  119. }
  120. /**
  121. * 修复路径操纵bug
  122. *
  123. * @param param
  124. * @return
  125. */
  126. private static String filterPath(String param) {
  127. Pattern pattern = compile("[/\\:*?<>|]");
  128. Matcher matcher = pattern.matcher(param);
  129. param = matcher.replaceAll("");
  130. return param;
  131. }
  132. /**
  133. * 本地文件上传接口
  134. *
  135. * @param file 上传的文件
  136. * @return 访问地址
  137. * @throws Exception
  138. */
  139. @Override
  140. public String uploadFile(MultipartFile file) throws Exception {
  141. String name = FileUploadUtils.upload(localFilePath, file);
  142. return name;
  143. }
  144. @Override
  145. public String uploadFile(MultipartFile file, String busType) throws Exception {
  146. String name = FileUploadUtils.upload(localFilePath, file, busType);
  147. return name;
  148. }
  149. @Override
  150. public void downloadFile(HttpServletResponse response, String filePath,String realName) {
  151. ByteArrayOutputStream out = null;
  152. try {
  153. filePath = localFilePath + filePath;
  154. filePath = URLDecoder.decode(filePath, "UTF-8");
  155. out = FileDownUtils.downloadFile(filePath);
  156. String fileSuffix = FileDownUtils.getFileSuffix(filePath);
  157. String formFileName = UUID.randomUUID().toString() + fileSuffix;
  158. if (StringUtils.isNotEmpty(realName)){
  159. formFileName = realName;
  160. }
  161. String userAgent = request.getHeader("User-Agent");
  162. // 针对IE或者以IE为内核的浏览器:
  163. if (StringUtils.isNotEmpty(userAgent) && (userAgent.contains("MSIE") || userAgent.contains("Trident"))) {
  164. formFileName = java.net.URLEncoder.encode(formFileName, "UTF-8");
  165. } else {
  166. // 非IE浏览器的处理:
  167. formFileName = new String(formFileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
  168. }
  169. response.reset();
  170. response.setCharacterEncoding("UTF-8");
  171. response.addHeader("Content-Disposition", "attachment;filename=" + formFileName);
  172. response.addHeader("Content-Length", "" + out.size());
  173. out.writeTo(response.getOutputStream());
  174. response.setContentType("application/octet-stream");
  175. out.flush();
  176. out.close();
  177. } catch (IOException e) {
  178. log.error("文件下载失败! ");
  179. e.printStackTrace();
  180. } finally {
  181. try {
  182. if (out != null) {
  183. out.close();
  184. }
  185. } catch (IOException e) {
  186. e.printStackTrace();
  187. }
  188. }
  189. }
  190. @Override
  191. public String getRelativePath(String path) {
  192. if (ObjectUtil.isEmpty(path)) {
  193. return null;
  194. }
  195. if (path.startsWith(this.localFilePath)) {
  196. return path.substring(this.localFilePath.length());
  197. }
  198. return path;
  199. }
  200. private void dealHeader(Map<String, Object> dataMap, Document document, BaseFont abf, BaseFont fs) throws
  201. DocumentException {
  202. //处理标题
  203. Paragraph p = new Paragraph(dataMap.get("title").toString(), new Font(fs, 20, Font.NORMAL));
  204. p.setAlignment(Paragraph.ALIGN_CENTER);
  205. //段落下空白
  206. p.setSpacingAfter(10f);
  207. document.add(p);
  208. //日期
  209. // String blankStr1 = " ";
  210. // String blankStr2 = " ";
  211. // Paragraph p2 = new Paragraph(dataMap.get("orgName") + blankStr1 + dataMap.get("dateStr") + blankStr2, new Font(abf, 10, Font.NORMAL));
  212. // p2.setAlignment(Paragraph.ALIGN_RIGHT);
  213. // document.add(p2);
  214. }
  215. @Override
  216. public String generateEduTrainingPdf(Map<String, Object> data) throws Exception {
  217. String fileName = filterPath(data.get("fileName").toString());
  218. PdfFilePathVo pathVo = getLocalFilePath("edu", fileName);
  219. String afterStr = StringEscapeUtils.escapeEcmaScript(pathVo.getTempFileName());
  220. log.info("开始生成教育培训登记簿,当前绝对地址为:{}", afterStr);
  221. final ItextPdfTableVo pdfTableVo = PdfUtil.createTable(pathVo.getTempFileName(), 6, 10);
  222. final Document document = pdfTableVo.getDocument();
  223. final PdfWriter writer = pdfTableVo.getWriter();
  224. final PdfPTable table = pdfTableVo.getTable();
  225. final BaseFont fs = pdfTableVo.getFs();
  226. final Font tableFont = pdfTableVo.getTableFont();
  227. document.open();
  228. PdfUtil.dealHeader(document, fs, "学 习 教 育 记 录", 24);
  229. PdfUtil.dealEduBody(document, table, tableFont, data);
  230. document.close();
  231. writer.close();
  232. PdfUtil.addPageNum(pathVo.getTempFileName(), pathVo.getAbsolutePath(), fs, tableFont);
  233. log.info("教育培训登记簿生成结束,当前绝对地址为:{}", afterStr);
  234. //此处返回 /statics/edu/xxx.pdf
  235. return this.prefix + pathVo.getRelativePath();
  236. }
  237. @Override
  238. public String generateResumptionPdf(Map<String, Object> data) throws Exception {
  239. PdfFilePathVo pathVo = getLocalFilePath("resumption", data.get("fileName").toString());
  240. String afterStr = StringEscapeUtils.escapeEcmaScript(pathVo.getAbsolutePath());
  241. log.info("开始生成履职登记簿,当前绝对地址为:{}", afterStr);
  242. Document document = new Document();
  243. PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pathVo.getAbsolutePath()));
  244. document.open();
  245. // 使用语言包字体
  246. BaseFont abf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
  247. // 外部字体
  248. BaseFont fs = BaseFont.createFont("/fonts/msyh.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
  249. Font tableFont = new Font(fs, 12, Font.NORMAL);
  250. PdfPTable table = new PdfPTable(10);
  251. table.setSpacingBefore(16f);
  252. table.setWidthPercentage(95L);
  253. this.dealHeader(data, document, abf, fs);
  254. PdfUtil.dealResumptionBody(document, table, tableFont, data);
  255. document.close();
  256. writer.close();
  257. log.info("履职登记簿生成结束,当前绝对地址为:{}", afterStr);
  258. //此处返回 /statics/edu/xxx.pdf
  259. return this.prefix + pathVo.getRelativePath();
  260. }
  261. @Override
  262. public String generateSafeCheckPdf(SafeCheckTaskRegisterBookVo data) throws Exception {
  263. PdfFilePathVo pathVo = getLocalFilePath("safeCheck", data.getDest());
  264. String afterStr = StringEscapeUtils.escapeEcmaScript(pathVo.getTempFileName());
  265. log.info("开始生成安全检查登记簿,当前绝对地址为:{}", afterStr);
  266. final ItextPdfTableVo pdfTableVo = PdfUtil.createTable(pathVo.getTempFileName(), 14, 10);
  267. final Document document = pdfTableVo.getDocument();
  268. final PdfWriter writer = pdfTableVo.getWriter();
  269. final PdfPTable table = pdfTableVo.getTable();
  270. final BaseFont fs = pdfTableVo.getFs();
  271. final Font tableFont = pdfTableVo.getTableFont();
  272. PdfUtil.dealHeader(document, fs, "安全保卫检查情况登记簿", 24);
  273. PdfUtil.dealSafeCheckPBody(document, table, tableFont, data);
  274. document.close();
  275. writer.close();
  276. PdfUtil.addPageNum(pathVo.getTempFileName(), pathVo.getAbsolutePath(), fs, tableFont);
  277. log.info("安全检查登记簿生成结束,当前绝对地址为:{}", afterStr);
  278. //此处返回 /statics/edu/xxx.pdf
  279. return this.prefix + pathVo.getRelativePath();
  280. }
  281. @Override
  282. public String generateAccessPdf(AccessPdf data) throws Exception {
  283. PdfFilePathVo pathVo = getLocalFilePath("access", data.getDest());
  284. String afterStr = StringEscapeUtils.escapeEcmaScript(pathVo.getAbsolutePath());
  285. log.info("开始生成监控调阅登记簿,当前绝对地址为:{}", afterStr);
  286. final ItextPdfTableVo pdfTableVo = PdfUtil.createTable(pathVo.getAbsolutePath(), 19, 10);
  287. final Document document = pdfTableVo.getDocument();
  288. final PdfWriter writer = pdfTableVo.getWriter();
  289. final PdfPTable table = pdfTableVo.getTable();
  290. final BaseFont fs = pdfTableVo.getFs();
  291. final Font tableFont = pdfTableVo.getTableFont();
  292. PdfUtil.dealHeader(document, fs, "监控调阅情况登记簿", 14);
  293. String checkTime = data.getTaskStartTime();
  294. String checkUser = data.getCheckUser();
  295. Font titleFont = new Font(fs, 10, Font.NORMAL);
  296. PdfUtil.createPDFCell(titleFont, table, "调阅单位", Element.ALIGN_MIDDLE, 4, 1);
  297. PdfUtil.createPDFCell(titleFont, table, data.getOrgName(), Element.ALIGN_MIDDLE, 6, 1);
  298. PdfUtil.createPDFCell(titleFont, table, "调阅人", Element.ALIGN_MIDDLE, 3, 1);
  299. PdfUtil.createPDFCell(titleFont, table, checkUser, Element.ALIGN_MIDDLE, 6, 1);
  300. PdfUtil.createPDFCell(titleFont, table, "调阅时间", Element.ALIGN_MIDDLE, 4, 1);
  301. PdfUtil.createPDFCell(titleFont, table, checkTime, Element.ALIGN_MIDDLE, 15, 1);
  302. PdfUtil.createPDFCell(titleFont, table, "调阅人签字", Element.ALIGN_MIDDLE, 4, 1);
  303. List<String> list = new ArrayList<>();
  304. list.add(data.getSignImg());
  305. dealImageCell(list, table, 1, 70, 40,15,1);
  306. PdfUtil.createPDFCell(titleFont, table, "监控调阅情况", Element.ALIGN_MIDDLE, 19, 1);
  307. PdfUtil.dealAccessPBody(document, table, tableFont, titleFont, data.getDataVos());
  308. document.add(table);
  309. document.close();
  310. writer.close();
  311. log.info("监控调阅登记簿生成结束,当前绝对地址为:{}", afterStr);
  312. //此处返回 /statics/edu/xxx.pdf
  313. return this.prefix + pathVo.getRelativePath();
  314. }
  315. @Override
  316. public String generateDrillPdf(Map<String, Object> data) throws Exception {
  317. PdfFilePathVo pathVo = getLocalFilePath("drill", data.get("fileName").toString());
  318. String afterStr = StringEscapeUtils.escapeEcmaScript(pathVo.getTempFileName());
  319. log.info("开始生成预案演练登记簿,当前绝对地址为:{}", afterStr);
  320. final ItextPdfTableVo pdfTableVo = PdfUtil.createTable(pathVo.getTempFileName(), 6, 10);
  321. final Document document = pdfTableVo.getDocument();
  322. final PdfWriter writer = pdfTableVo.getWriter();
  323. final PdfPTable table = pdfTableVo.getTable();
  324. final BaseFont fs = pdfTableVo.getFs();
  325. final Font tableFont = pdfTableVo.getTableFont();
  326. document.open();
  327. PdfUtil.dealHeader(document, fs, "预 案 演 练 记 录", 24);
  328. PdfUtil.dealDrillBody(document, table, tableFont, data);
  329. document.close();
  330. writer.close();
  331. log.info("预案演练登记簿生成结束,当前绝对地址为:{}", afterStr);
  332. PdfUtil.addPageNum(pathVo.getTempFileName(), pathVo.getAbsolutePath(), fs, tableFont);
  333. //此处返回 /statics/edu/xxx.pdf
  334. return this.prefix + pathVo.getRelativePath();
  335. }
  336. @Override
  337. public String generateOutInPdf(Map<String, Object> data) throws Exception {
  338. PdfFilePathVo pathVo = getLocalFilePath("visit", data.get("fileName").toString());
  339. String afterStr = StringEscapeUtils.escapeEcmaScript(pathVo.getTempFileName());
  340. log.info("开始生成来访管理登记簿,当前绝对地址为:{}", afterStr);
  341. final ItextPdfTableVo pdfTableVo = PdfUtil.createTable(pathVo.getTempFileName(), 6, 10);
  342. final Document document = pdfTableVo.getDocument();
  343. final PdfWriter writer = pdfTableVo.getWriter();
  344. final PdfPTable table = pdfTableVo.getTable();
  345. final BaseFont fs = pdfTableVo.getFs();
  346. final Font tableFont = pdfTableVo.getTableFont();
  347. PdfUtil.dealHeader(document, fs, "来 访 管 理 登 记 簿", 24);
  348. PdfUtil.dealOutInBody(document, table, tableFont, data);
  349. document.close();
  350. writer.close();
  351. log.info("来访管理登记簿生成结束,当前绝对地址为:{}", afterStr);
  352. PdfUtil.addPageNum(pathVo.getTempFileName(), pathVo.getAbsolutePath(), fs, tableFont);
  353. //此处返回 /statics/edu/xxx.pdf
  354. return this.prefix + pathVo.getRelativePath();
  355. }
  356. @Override
  357. public String uploadFileBase64(FileBase64Vo file) throws Exception {
  358. String filePath = FileUploadUtils.uploadBase64(localFilePath, file);
  359. return filePath;
  360. }
  361. /**
  362. * 履职转pdf
  363. *
  364. * @param dest
  365. * @throws IOException
  366. * @throws DocumentException
  367. */
  368. public void dataToPdf(String dest) throws IOException, DocumentException {
  369. Document document = new Document();
  370. PdfWriter.getInstance(document, new FileOutputStream(dest));
  371. document.open();
  372. // 使用语言包字体
  373. BaseFont abf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
  374. //字体
  375. Font font = new Font(abf, 8);
  376. //段落
  377. Paragraph p = new Paragraph("测试结算单", new Font(abf, 12, Font.BOLD));
  378. p.setAlignment(Paragraph.ALIGN_CENTER);
  379. document.add(p);
  380. //表格
  381. PdfPTable table = new PdfPTable(8);//numcolumns:列数
  382. table.setSpacingBefore(16f);//表格与上面段落的空隙
  383. //表格列创建并赋值
  384. PdfPCell cell = new PdfPCell(new Phrase("单位名称:测试有限公司", font));
  385. cell.setHorizontalAlignment(Element.ALIGN_LEFT);//居中
  386. cell.disableBorderSide(13);//去除左右上边框,保留下边框
  387. cell.setColspan(4);//合并列数
  388. table.addCell(cell);
  389. cell = new PdfPCell(new Phrase("日期:2020-06-05", font));
  390. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  391. cell.disableBorderSide(13);
  392. cell.setColspan(3);
  393. table.addCell(cell);
  394. cell = new PdfPCell(new Phrase("单位(元)", font));
  395. cell.setHorizontalAlignment(Element.ALIGN_LEFT);
  396. cell.disableBorderSide(13);
  397. cell.setColspan(1);
  398. table.addCell(cell);
  399. //首行
  400. cell = new PdfPCell(new Phrase("期间", font));
  401. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  402. cell.setColspan(2);
  403. table.addCell(cell);
  404. cell = new PdfPCell(new Phrase("月份", font));
  405. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  406. table.addCell(cell);
  407. cell = new PdfPCell(new Phrase("分类", font));
  408. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  409. table.addCell(cell);
  410. cell = new PdfPCell(new Phrase("年利率", font));
  411. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  412. table.addCell(cell);
  413. cell = new PdfPCell(new Phrase("日利率", font));
  414. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  415. table.addCell(cell);
  416. cell = new PdfPCell(new Phrase("基数", font));
  417. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  418. table.addCell(cell);
  419. cell = new PdfPCell(new Phrase("利息", font));
  420. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  421. table.addCell(cell);
  422. cell = new PdfPCell(new Phrase("起始日:2020-03-26\n" +
  423. "结束日:2020-04-25", font));
  424. cell.setPadding(16f);
  425. cell.setVerticalAlignment(Element.ALIGN_CENTER);
  426. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  427. cell.setRowspan(3);
  428. cell.setColspan(2);
  429. table.addCell(cell);
  430. cell = new PdfPCell(new Phrase("4", font));
  431. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  432. table.addCell(cell);
  433. cell = new PdfPCell(new Phrase("资金", font));
  434. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  435. table.addCell(cell);
  436. cell = new PdfPCell(new Phrase("1.10%", font));
  437. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  438. table.addCell(cell);
  439. cell = new PdfPCell(new Phrase("0.000031", font));
  440. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  441. table.addCell(cell);
  442. cell = new PdfPCell(new Phrase("10598164.91", font));
  443. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  444. table.addCell(cell);
  445. cell = new PdfPCell(new Phrase("325.01", font));
  446. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  447. table.addCell(cell);
  448. cell = new PdfPCell(new Phrase("4", font));
  449. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  450. table.addCell(cell);
  451. cell = new PdfPCell(new Phrase("资金", font));
  452. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  453. table.addCell(cell);
  454. cell = new PdfPCell(new Phrase("1.10%", font));
  455. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  456. table.addCell(cell);
  457. cell = new PdfPCell(new Phrase("0.000031", font));
  458. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  459. table.addCell(cell);
  460. cell = new PdfPCell(new Phrase("-", font));
  461. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  462. table.addCell(cell);
  463. cell = new PdfPCell(new Phrase("-", font));
  464. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  465. table.addCell(cell);
  466. cell = new PdfPCell(new Phrase("4", font));
  467. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  468. table.addCell(cell);
  469. cell = new PdfPCell(new Phrase("资金", font));
  470. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  471. table.addCell(cell);
  472. cell = new PdfPCell(new Phrase("1.10%", font));
  473. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  474. table.addCell(cell);
  475. cell = new PdfPCell(new Phrase("0.000031", font));
  476. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  477. table.addCell(cell);
  478. cell = new PdfPCell(new Phrase("-", font));
  479. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  480. table.addCell(cell);
  481. cell = new PdfPCell(new Phrase("-", font));
  482. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  483. table.addCell(cell);
  484. cell = new PdfPCell(new Phrase("合计", font));
  485. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  486. cell.setColspan(7);
  487. table.addCell(cell);
  488. cell = new PdfPCell(new Phrase("325.01", font));
  489. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  490. table.addCell(cell);
  491. cell = new PdfPCell(new Phrase("会计制单:", font));
  492. cell.setHorizontalAlignment(Element.ALIGN_LEFT);
  493. cell.disableBorderSide(14);
  494. cell.setColspan(4);
  495. table.addCell(cell);
  496. cell = new PdfPCell(new Phrase("复核:", font));
  497. cell.setHorizontalAlignment(Element.ALIGN_LEFT);
  498. cell.disableBorderSide(14);
  499. cell.setColspan(4);
  500. table.addCell(cell);
  501. table.setSpacingBefore(16f);
  502. document.add(table);
  503. //下一页
  504. document.newPage();
  505. //段落
  506. Paragraph p1 = new Paragraph("下一页测试结算单", new Font(abf, 12, Font.BOLD));
  507. p1.setAlignment(Paragraph.ALIGN_CENTER);
  508. document.add(p1);
  509. //表格
  510. table = new PdfPTable(8);//numcolumns:列数
  511. table.setSpacingBefore(16f);//表格与上面段落的空隙
  512. //表格列创建并赋值
  513. cell = new PdfPCell(new Phrase("单位名称:测试有限公司", font));
  514. cell.setHorizontalAlignment(Element.ALIGN_LEFT);//居中
  515. cell.disableBorderSide(13);//去除左右上边框,保留下边框
  516. cell.setColspan(4);//合并列数
  517. table.addCell(cell);
  518. cell = new PdfPCell(new Phrase("日期:2020-06-05", font));
  519. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  520. cell.disableBorderSide(13);
  521. cell.setColspan(3);
  522. table.addCell(cell);
  523. cell = new PdfPCell(new Phrase("单位(元)", font));
  524. cell.setHorizontalAlignment(Element.ALIGN_LEFT);
  525. cell.disableBorderSide(13);
  526. cell.setColspan(1);
  527. table.addCell(cell);
  528. //首行
  529. cell = new PdfPCell(new Phrase("期间", font));
  530. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  531. cell.setColspan(2);
  532. table.addCell(cell);
  533. cell = new PdfPCell(new Phrase("月份", font));
  534. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  535. table.addCell(cell);
  536. cell = new PdfPCell(new Phrase("分类", font));
  537. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  538. table.addCell(cell);
  539. cell = new PdfPCell(new Phrase("年利率", font));
  540. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  541. table.addCell(cell);
  542. cell = new PdfPCell(new Phrase("日利率", font));
  543. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  544. table.addCell(cell);
  545. cell = new PdfPCell(new Phrase("基数", font));
  546. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  547. table.addCell(cell);
  548. cell = new PdfPCell(new Phrase("利息", font));
  549. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  550. table.addCell(cell);
  551. cell = new PdfPCell(new Phrase("起始日:2020-04-26\n" +
  552. "结束日:2020-05-25", font));
  553. cell.setPadding(16f);
  554. cell.setVerticalAlignment(Element.ALIGN_CENTER);
  555. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  556. cell.setColspan(2);
  557. table.addCell(cell);
  558. cell = new PdfPCell(new Phrase("4", font));
  559. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  560. table.addCell(cell);
  561. cell = new PdfPCell(new Phrase("资金", font));
  562. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  563. table.addCell(cell);
  564. cell = new PdfPCell(new Phrase("1.10%", font));
  565. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  566. table.addCell(cell);
  567. cell = new PdfPCell(new Phrase("0.000031", font));
  568. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  569. table.addCell(cell);
  570. cell = new PdfPCell(new Phrase("10598164.91", font));
  571. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  572. table.addCell(cell);
  573. cell = new PdfPCell(new Phrase("325.01", font));
  574. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  575. table.addCell(cell);
  576. cell = new PdfPCell(new Phrase("合计", font));
  577. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  578. cell.setColspan(7);
  579. table.addCell(cell);
  580. cell = new PdfPCell(new Phrase("325.01", font));
  581. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  582. table.addCell(cell);
  583. cell = new PdfPCell(new Phrase("会计制单:", font));
  584. cell.setHorizontalAlignment(Element.ALIGN_LEFT);
  585. cell.disableBorderSide(14);
  586. cell.setColspan(4);
  587. table.addCell(cell);
  588. cell = new PdfPCell(new Phrase("复核:", font));
  589. cell.setHorizontalAlignment(Element.ALIGN_LEFT);
  590. cell.disableBorderSide(14);
  591. cell.setColspan(4);
  592. table.addCell(cell);
  593. table.setSpacingBefore(16f);
  594. document.add(table);
  595. document.close();
  596. }
  597. @Override
  598. public String absolutePath(String path) {
  599. if (ObjectUtil.isEmpty(path)) {
  600. return StringUtil.EMPTY_STRING;
  601. }
  602. if (path.startsWith(this.localFilePath)) {
  603. return path;
  604. }
  605. if (path.startsWith(this.prefix)) {
  606. return this.localFilePath + path.substring(this.prefix.length());
  607. }
  608. return StringUtil.EMPTY_STRING;
  609. }
  610. @Override
  611. public InputStream getFileStream(String path) throws IOException {
  612. String absolutePath = this.absolutePath(path);
  613. File file = FileUtils.getFile(absolutePath);
  614. return Files.newInputStream(file.toPath());
  615. }
  616. @Override
  617. public void registerBookCompressPdf(ExportPdfDto pdfDto, HttpServletResponse response) throws IOException {
  618. final List<CoreRegisterBookPdfPageVo> registerBookPdfList = pdfDto.getRegisterBookPdfList();
  619. try {
  620. String zipName = URLEncoder.encode(pdfDto.getFileName() + DateHelper.getDateString(new Date()) + ".zip", "UTF-8");
  621. final CountDownLatch count = new CountDownLatch(registerBookPdfList.size());
  622. ServletOutputStream outputStream = response.getOutputStream();
  623. ZipOutputStream zos = new ZipOutputStream(outputStream);
  624. response.setContentType("application/octet-stream");
  625. response.setHeader("Content-Disposition", "attachment; filename=" + zipName);
  626. List<PdfToZipTempVo> pdfToZipTempVoList = registerBookPdfList.parallelStream().map(pdf -> {
  627. return resolve(pdf, count);
  628. }).filter(Objects::nonNull)
  629. .collect(Collectors.toList());
  630. count.await();
  631. pdfToZipTempVoList.removeIf(pdfToZipTempVo -> !FileUtil.exist(pdfToZipTempVo.getFile()));
  632. log.info("登记簿全部下载完成,开始压缩文件,数量:{}", pdfToZipTempVoList.size());
  633. for (PdfToZipTempVo tempVo : pdfToZipTempVoList) {
  634. log.info("当前开始处理第{}个文件 ", pdfToZipTempVoList.indexOf(tempVo) + 1);
  635. deal(zos, tempVo);
  636. }
  637. zos.flush();
  638. zos.close();
  639. outputStream.close();
  640. log.info("登记簿批量导出压缩文件完成,文件数量:{}", pdfToZipTempVoList.size());
  641. } catch (Throwable e) {
  642. String errMsg = String.format("登记簿导出失败:%s", e);
  643. log.error(errMsg);
  644. } finally {
  645. final File temp = new File(TEMP_DIR_NAME);
  646. if (temp.exists()) {
  647. FileUtil.del(temp);
  648. log.info("临时目录已删除");
  649. }
  650. }
  651. }
  652. public PdfToZipTempVo resolve(CoreRegisterBookPdfPageVo pdf, CountDownLatch count) {
  653. final File temp = new File(TEMP_DIR_NAME);
  654. if (!temp.exists()) {
  655. temp.mkdirs();
  656. }
  657. InputStream inputStream;
  658. try {
  659. inputStream = getFileStream(pdf.getFileUrl());
  660. if (ObjectUtil.isEmpty(inputStream)) {
  661. log.error("登记簿导出失败,文件不存在,文件名:{}", pdf.getFileUrl());
  662. throw new RuntimeException("登记簿导出失败,文件不存在");
  663. }
  664. final String pdfFileName = pdf.getFileName();
  665. //pdfFileName==null的时候在下面会报错此处加个判断,要处理问题还需要在问题源头除处理
  666. // registerBookPdfBatchExportTempDir (Is a directory)
  667. if (StringUtils.isEmpty(pdfFileName)) {
  668. throw new RuntimeException("登记簿导出失败,文件不存在");
  669. }
  670. final PdfToZipTempVo tempVo = new PdfToZipTempVo();
  671. //tempVo.setBytes(bytes);
  672. tempVo.setFileName(pdfFileName);
  673. tempVo.setOrgId(pdf.getOrgId());
  674. tempVo.setOrgName(pdf.getOrgName());
  675. tempVo.setRegisterBookType(RegisterBookType.getEnums(pdf.getRegisterBookType()));
  676. final File file = new File(temp + File.separator + pdfFileName);
  677. final FileOutputStream outputStream = new FileOutputStream(file);
  678. byte[] buffer = new byte[4096];
  679. int len;
  680. while ((len = inputStream.read(buffer)) > 0) {
  681. outputStream.write(buffer, 0, len);
  682. }
  683. outputStream.close();
  684. inputStream.close();
  685. tempVo.setFile(file);
  686. final List<IdName<Long, String>> idNameList = pdf.getOrgList();
  687. if (ObjectUtil.isEmpty(idNameList)) {
  688. tempVo.setEntryName(File.separator + RegisterBookType.getEnums(pdf.getRegisterBookType()).getText() + File.separator + pdfFileName);
  689. return tempVo;
  690. }
  691. StringJoiner stringJoiner = new StringJoiner(File.separator);
  692. for (IdName<Long, String> org : idNameList) {
  693. stringJoiner.add(org.getName());
  694. if (idNameList.lastIndexOf(org) == idNameList.size() - 1) {
  695. stringJoiner.add(RegisterBookType.getEnums(pdf.getRegisterBookType()).getText() + File.separator + pdfFileName);
  696. }
  697. }
  698. tempVo.setEntryName(stringJoiner.toString());
  699. return tempVo;
  700. } catch (Exception e) {
  701. log.error("读取文件失败", e);
  702. return null;
  703. } finally {
  704. count.countDown();
  705. }
  706. }
  707. public void deal(ZipOutputStream zos, PdfToZipTempVo zipTempVo) throws Throwable {
  708. zos.setEncoding("GBK");
  709. FileInputStream fileInputStream = new FileInputStream(zipTempVo.getFile());
  710. zos.putNextEntry(new ZipEntry(zipTempVo.getEntryName()));
  711. byte[] buffer = new byte[4096];
  712. int len;
  713. while ((len = fileInputStream.read(buffer)) > 0) {
  714. zos.write(buffer, 0, len);
  715. }
  716. zos.closeEntry();
  717. fileInputStream.close();
  718. }
  719. private List<SysOrgVO> getChildrenList(Long orgId) {
  720. List<SysOrgVO> cacheList = RedisUtils.getCacheList(CacheConstants.ORG_CACHE_LIST_KEY);
  721. return cacheList.stream()
  722. .filter(org -> ObjectUtil.equal(org.getParentId(), orgId))
  723. .collect(Collectors.toList());
  724. }
  725. private SysOrgVO getCurOrg(Long orgId) {
  726. List<SysOrgVO> cacheList = RedisUtils.getCacheList(CacheConstants.ORG_CACHE_LIST_KEY);
  727. return cacheList.stream()
  728. .filter(org -> ObjectUtil.equal(org.getId(), orgId))
  729. .findFirst().get();
  730. }
  731. @Override
  732. public void cutFileCompress(CoreRegisterBookPdfExportDto pdfDto) {
  733. SysOrgVO org = getCurOrg(pdfDto.getOrgId());
  734. Date date = new Date();
  735. String fileName = pdfDto.getIsRegisterBookPage() ? org.getName() + "_登记簿_" : org.getName() + "_数据报表_";
  736. //判断需要分几片导出
  737. List<List<CoreRegisterBookPdfPageVo>> lists = checkSubList(pdfDto);
  738. int num = 1;
  739. try {
  740. for (List<CoreRegisterBookPdfPageVo> list : lists) {
  741. CountDownLatch count = new CountDownLatch(list.size());
  742. String zipName = null;
  743. String str = lists.size() == 1 ? "" : "_part_" + num;
  744. String fileNameStr = fileName + DateHelper.getDateString(new Date()) + str;
  745. zipName = URLEncoder.encode(fileNameStr + ".zip", "UTF-8");
  746. List<PdfToZipTempVo> pdfToZipTempVoList = list.parallelStream().map(pdf -> {
  747. return resolve(pdf, count);
  748. }).filter(Objects::nonNull)
  749. .collect(Collectors.toList());
  750. pdfToZipTempVoList.removeIf(pdfToZipTempVo -> !FileUtil.exist(pdfToZipTempVo.getFile()));
  751. log.info("登记簿全部下载完成,开始压缩文件,数量:{}", pdfToZipTempVoList.size());
  752. String encodedFileName = URLEncoder.encode(CacheConstants.REGISTER_PDF_FILE_KEY + DateHelper.getDateString(date) + str + ".zip", "UTF-8");
  753. String filePath = this.localFilePath + File.separator + encodedFileName;
  754. File file = FileUtils.getFile(filePath);
  755. FileOutputStream fos = new FileOutputStream(file);
  756. ZipOutputStream zos = new ZipOutputStream(fos);
  757. long fileSize = 0L;
  758. for (PdfToZipTempVo tempVo : pdfToZipTempVoList) {
  759. fileSize += tempVo.getFile().length();
  760. log.info("当前开始处理第{}个文件 ", pdfToZipTempVoList.indexOf(tempVo) + 1);
  761. deal(zos, tempVo);
  762. }
  763. zos.flush();
  764. fos.flush();
  765. zos.close();
  766. fos.close();
  767. num++;
  768. saveFileDataToRedis(org, date, zipName, filePath, fileSize, pdfDto);
  769. }
  770. } catch (Throwable e) {
  771. throw new RuntimeException(e);
  772. } finally {
  773. File file = new File(TEMP_DIR_NAME);
  774. if (file.exists()) {
  775. FileUtil.del(file);
  776. }
  777. }
  778. }
  779. private void saveFileDataToRedis(SysOrgVO org, Date date, String zipName, String localFileName, long fileSize, CoreRegisterBookPdfExportDto pdfDto) throws UnsupportedEncodingException {
  780. PdfLocalFileTempVo pdfLocalFileTempVo = new PdfLocalFileTempVo();
  781. pdfLocalFileTempVo.setOrgId(pdfDto.getOrgId());
  782. pdfLocalFileTempVo.setOrgName(org.getName());
  783. pdfLocalFileTempVo.setOrgPath(org.getPath());
  784. pdfLocalFileTempVo.setLocalFileName(localFileName);
  785. pdfLocalFileTempVo.setZipName(URLDecoder.decode(zipName, "UTF-8"));
  786. pdfLocalFileTempVo.setFileSize(changeUnit(fileSize));
  787. pdfLocalFileTempVo.setDownLoadTime(DateUtil.format(date, "yyyy-MM-dd HH:mm:ss"));
  788. pdfLocalFileTempVo.setIsRegisterBookPage(pdfDto.getIsRegisterBookPage());
  789. pdfLocalFileTempVo.setCreateTime(new Date());
  790. //此处localFileName 为文件的绝对路径,存在redis延迟队列中,一个小时后删除文件
  791. localFileName = localFileName.replace(this.localFilePath + File.separator, "");
  792. //此处localFileName 为文件名称,存入redis中,用于页面展示文件名称,下载
  793. //RedisUtils.setCacheObject(URLDecoder.decode(localFileName, "UTF-8"), JSON.toJSONString(pdfLocalFileTempVo),true);
  794. final BoundValueOperations ops = redisTemplate.boundValueOps(URLDecoder.decode(localFileName, "UTF-8"));
  795. ops.set(JSON.toJSONString(pdfLocalFileTempVo));
  796. ops.expireAt(DateUtil.endOfDay(new Date()));
  797. }
  798. private List<List<CoreRegisterBookPdfPageVo>> checkSubList(CoreRegisterBookPdfExportDto pdfDto) {
  799. List<List<CoreRegisterBookPdfPageVo>> list = new ArrayList<>();
  800. List<CoreRegisterBookPdfPageVo> registerBookPdfList = pdfDto.getDataList();
  801. if (CollectionUtil.isEmpty(registerBookPdfList)) {
  802. throw new RuntimeException("暂无可下载数据!");
  803. }
  804. //小于3000条直接导出
  805. if (registerBookPdfList.size() < 3000) {
  806. list.add(registerBookPdfList);
  807. return list;
  808. }
  809. List<SysOrgVO> orgList = getChildrenList(pdfDto.getOrgId());
  810. //大于3000条需要分片
  811. return splitList(registerBookPdfList, orgList, 3000);
  812. }
  813. public static List<List<CoreRegisterBookPdfPageVo>> splitList(List<CoreRegisterBookPdfPageVo> list, List<SysOrgVO> orgList, int size) {
  814. // 根据机构分组
  815. List<List<CoreRegisterBookPdfPageVo>> collect = orgList.stream().map(org -> {
  816. List<CoreRegisterBookPdfPageVo> arrayList = new ArrayList<>();
  817. for (CoreRegisterBookPdfPageVo pdf : list) {
  818. if (pdf.getOrgPath().startsWith(org.getPath())) {
  819. arrayList.add(pdf);
  820. }
  821. }
  822. return arrayList;
  823. }).filter(ObjectUtil::isNotEmpty).collect(Collectors.toList());
  824. // 合并不满3000的数组
  825. List<List<CoreRegisterBookPdfPageVo>> merged = new LinkedList<>();
  826. List<CoreRegisterBookPdfPageVo> current = new ArrayList<>();
  827. for (List<CoreRegisterBookPdfPageVo> group : collect) {
  828. if (group.size() >= size) {
  829. merged.add(group);
  830. } else {
  831. current.addAll(group);
  832. if (current.size() >= size) {
  833. merged.add(current);
  834. current = new ArrayList<>();
  835. }
  836. }
  837. }
  838. if (!current.isEmpty()) {
  839. merged.add(current);
  840. }
  841. return merged;
  842. //return merged.stream().limit(size).collect(Collectors.toList());
  843. }
  844. public String changeUnit(Long fileSize) {
  845. if (fileSize == null || fileSize == 0) {
  846. return "0";
  847. }
  848. //将fileSize转换为MB,保留整数
  849. BigDecimal fileSizeMB = new BigDecimal(fileSize).divide(new BigDecimal(1024 * 1024), 2, BigDecimal.ROUND_HALF_UP);
  850. return fileSizeMB.toString();
  851. }
  852. @Override
  853. public void deletedZipFile() {
  854. final File dir = FileUtils.getFile(this.localFilePath);
  855. final File[] files = dir.listFiles();
  856. if (ObjectUtil.isNull(files) || ObjectUtil.isEmpty(files)) {
  857. return;
  858. }
  859. Arrays.stream(files)
  860. .filter(file -> file.getName().startsWith(CacheConstants.REGISTER_PDF_FILE_KEY))
  861. .filter(file -> file.getName().endsWith(".zip"))
  862. .forEach(FileUtil::del);
  863. }
  864. @Override
  865. public byte[] readFile(String path) throws IOException {
  866. if (ObjectUtil.isEmpty(path)) {
  867. throw new RuntimeException("文件地址无效");
  868. }
  869. // 对网络地址进行解码
  870. path = URLDecoder.decode(path, "UTF-8");
  871. // 读取图片文件
  872. URL url = new URL(path);
  873. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  874. conn.setRequestMethod("GET");
  875. conn.setConnectTimeout(5 * 1000);
  876. InputStream stream = conn.getInputStream();
  877. // FileUtil.del("d:\\1111.jpg");
  878. //FileUtil.writeFromStream(stream,"d:\\1111.jpg");
  879. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  880. try (BufferedInputStream bis = new BufferedInputStream(stream)) {
  881. // 设置响应类型
  882. // response.setContentType("image/*");
  883. // response.setHeader("Content-Length", String.valueOf(stream.available()));
  884. // 将文件流发送给前端
  885. byte[] buffer = new byte[1024];
  886. int bytesRead;
  887. while ((bytesRead = bis.read(buffer)) != -1) {
  888. outStream.write(buffer, 0, bytesRead);
  889. }
  890. byte[] r = outStream.toByteArray();
  891. if (r[0] == 10) {
  892. byte[] r1 = new byte[r.length - 1];
  893. ArrayUtil.copy(r, 1, r1, 0, r1.length);
  894. return r1;
  895. } else {
  896. return r;
  897. }
  898. }
  899. }
  900. }