接受文件类型 是否删除 响应类

  1. private void doExportFile(EngineFileType fileOutputType, Boolean deleteFile,
  2. HttpServletResponse response) throws IOException {
  3. String docFileName = DOC_FILE_NAME + "_" + IdUtil.fastSimpleUUID();
  4. String filePath = doExportFile(fileOutputType, docFileName);
  5. String downloadFileName = DOC_FILE_NAME + fileOutputType.getFileSuffix(); //下载后的文件名
  6. try {
  7. // 读取,返回
  8. ServletUtils.writeAttachment(response, downloadFileName, FileUtil.readBytes(filePath));
  9. } finally {
  10. handleDeleteFile(deleteFile, filePath);
  11. }
  12. }

输出文件到指定目录并返回文件路径

  1. /**
  2. * 输出文件,返回文件路径
  3. *
  4. * @param fileOutputType 文件类型
  5. * @param fileName 文件名, 无需 ".docx" 等文件后缀
  6. * @return 生成的文件所在路径
  7. */
  8. private String doExportFile(EngineFileType fileOutputType, String fileName) {
  9. try (HikariDataSource dataSource = buildDataSource()) {
  10. // 创建 screw 的配置
  11. Configuration config = Configuration.builder()
  12. .version(DOC_VERSION) // 版本 1.0.0
  13. .description(DOC_DESCRIPTION) // 描述 文档描述
  14. .dataSource(dataSource) // 数据源
  15. .engineConfig(buildEngineConfig(fileOutputType, fileName)) // 引擎配置
  16. .produceConfig(buildProcessConfig()) // 处理配置
  17. .build();
  18. // 执行 screw,生成数据库文档
  19. new DocumentationExecute(config).execute();
  20. return FILE_OUTPUT_DIR + File.separator + fileName + fileOutputType.getFileSuffix();
  21. }
  1. /**
  2. * 创建 screw 的引擎配置
  3. */
  4. private static EngineConfig buildEngineConfig(EngineFileType fileOutputType, String docFileName) {
  5. return EngineConfig.builder()
  6. .fileOutputDir(FILE_OUTPUT_DIR) // 生成文件路径
  7. .openOutputDir(false) // 打开目录
  8. .fileType(fileOutputType) // 文件类型
  9. .produceType(EngineTemplateType.velocity) // 文件类型
  10. .fileName(docFileName) // 自定义文件名称
  11. .build();
  12. }
  1. /**
  2. * 创建 screw 的处理配置,一般可忽略
  3. * 指定生成逻辑、当存在指定表、指定表前缀、指定表后缀时,将生成指定表,其余表不生成、并跳过忽略表配置
  4. */
  5. private static ProcessConfig buildProcessConfig() {
  6. return ProcessConfig.builder()
  7. .ignoreTablePrefix(Arrays.asList("QRTZ_", "ACT_")) // 忽略表前缀
  8. .build();
  9. }

输出附件

  1. /**
  2. * 返回附件
  3. *
  4. * @param response 响应
  5. * @param filename 文件名
  6. * @param content 附件内容
  7. * @throws IOException
  8. */
  9. public static void writeAttachment(HttpServletResponse response, String filename, byte[] content) throws IOException {
  10. // 设置 header 和 contentType
  11. response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
  12. response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
  13. // 输出附件
  14. IoUtil.write(response.getOutputStream(), false, content);
  15. }