The introduction
In a recent project, there was a requirement to check multiple records from a log table, write each record to a TXT file, and then package multiple TXT files into a ZIP download. Online to find some examples, write more cumbersome, my scene here is as long as each record into TXT and then packaged download, so a minimalist way to achieve.
Core implementation code
** @param jobLogIds Job log ID set * @param Response HttpServletResponse */ @override @Transactional(rollbackFor = Exception.class) public void downloadJobLogs(List<String> jobLogIds, Example Example = new Example(umijoblog.class); example.createCriteria().andIn("id", jobLogIds); List<UmiJobLog> umiJobLogs = this.umiJobLogMapper.selectByExample(example); String prefix = DateUtil.format(new Date(), "yyyyMMddHHmmss"); String downloadFileName = "JobLog" + prefix + ".zip"; String downloadFileName = "JobLog" + prefix + ".zip"; // Reset response, set response.reset(); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=" + downloadFileName); try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream())) { for (UmiJobLog jobLog : UmiJobLogs) {// Job logs are formatted as a String. String jobLogStr = getJobLogStr(jobLog); / / zip file into an entry zipOutputStream. PutNextEntry (new ZipEntry (jobLog. GetTaskName () + ". TXT ")); Write (jobLogstr.getBytes (" utF-8 ")); // Write the string to the zip entry zipOutputStream.write(jobLogstr.getBytes (" utF-8 ")); / / to complete the package items zipOutputStream. CloseEntry (); } } catch (IOException e) { e.printStackTrace(); }} private String getJobLogStr(umiJobLog umiJobLog) {private String getJobLogStr(umiJobLog umiJobLog) { final StringBuilder builder = new StringBuilder(); Builder.append (" Task name: "+ umijoblog.gettaskName ()); builder.append(System.getProperty("line.separator")); Builder.append (" Task type: "+ umijoblog.getetlType ()); builder.append(System.getProperty("line.separator")); Builder. Append (" scheduling name: "+ umiJobLog. GetScheduleName ()); builder.append(System.getProperty("line.separator")); Builder.append (" Task Status: "+ umijoblog.getStatus ()); builder.append(System.getProperty("line.separator")); Builder.append (" Task start time: "+ dateutil. format(umijoblog.getStartTime (), null)); builder.append(System.getProperty("line.separator")); Builder.append (" Task end time: "+ dateutil. format(umijoblog.getoverTime (), null)); builder.append(System.getProperty("line.separator")); return builder.toString(); }Copy the code