Skip to content

Commit

Permalink
基础代码生成文件下载功能实现
Browse files Browse the repository at this point in the history
  • Loading branch information
matevip committed Jul 10, 2020
1 parent deed030 commit 53d36f7
Show file tree
Hide file tree
Showing 5 changed files with 130 additions and 7 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ target/
.classpath
.project
logs/
temp/

# idea
.idea/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,9 @@ public class MateConstant {
* 树的根节点值
*/
public static final Long TREE_ROOT = -1L;
/**
* 允许的文件类型,可根据需求添加
*/
public static final String[] VALID_FILE_TYPE = {"xlsx", "zip"};

}
6 changes: 6 additions & 0 deletions mate-core/mate-starter-dependencies/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
<fastjson.version>1.2.71</fastjson.version>

<spring-boot-admin.version>2.2.3</spring-boot-admin.version>
<poi.version>4.1.2</poi.version>
</properties>

<dependencyManagement>
Expand Down Expand Up @@ -241,6 +242,11 @@
<artifactId>spring-boot-admin-server-ui</artifactId>
<version>${spring-boot-admin.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
</dependencies>
</dependencyManagement>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package vip.mate.core.web.util;

import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import vip.mate.core.common.constant.MateConstant;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;

@Slf4j
public class FileUtil {

/**
* 获取文件类型
*
* @param file 文件
* @return 文件类型
* @throws Exception Exception
*/
private static String getFileType(File file) throws Exception {
Preconditions.checkNotNull(file);
if (file.isDirectory()) {
throw new Exception("file不是文件");
}
String fileName = file.getName();
return fileName.substring(fileName.lastIndexOf(".") + 1);
}

/**
* 校验文件类型是否是允许下载的类型
*
* @param fileType fileType
* @return Boolean
*/
private static Boolean fileTypeIsValid(String fileType) {
Preconditions.checkNotNull(fileType);
fileType = StringUtils.lowerCase(fileType);
return ArrayUtils.contains(MateConstant.VALID_FILE_TYPE, fileType);
}

public static void download(String filePath, String fileName, Boolean delete, HttpServletResponse response) throws Exception {
File file = new File(filePath);
if (!file.exists()) {
throw new Exception("文件未找到");
}

String fileType = getFileType(file);
if (!fileTypeIsValid(fileType)) {
throw new Exception("暂不支持该类型文件下载");
}
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;fileName=" + java.net.URLEncoder.encode(fileName, "utf-8"));
response.setContentType(MediaType.MULTIPART_FORM_DATA_VALUE);
response.setCharacterEncoding("utf-8");
try (InputStream inputStream = new FileInputStream(file); OutputStream os = response.getOutputStream()) {
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
} finally {
if (delete) {
delete(filePath);
}
}
}

/**
* 递归删除文件或目录
*
* @param filePath 文件或目录
*/
public static void delete(String filePath) {
File file = new File(filePath);
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
Arrays.stream(files).forEach(f -> delete(f.getPath()));
}
}
file.delete();
}

public static ResponseEntity<FileSystemResource> export(File file) {
if (file == null) {
return null;
}
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new FileSystemResource(file));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
Expand All @@ -19,7 +21,10 @@
import vip.mate.code.util.GeneratorUtil;
import vip.mate.code.util.ZipUtil;
import vip.mate.core.common.api.Result;
import vip.mate.core.web.util.FileUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -57,9 +62,10 @@ public Result<List<TableInfo>> tableList(@RequestParam String dataSourceId) {

@ApiOperation(value = "代码生成并下载", notes = "代码生成并下载")
@PostMapping("/generator-code")
public Result<?> execute(@RequestParam String packageName, @RequestParam String prefix,
@RequestParam String modelName, @RequestParam String datasourceId,
@RequestParam String tableName) {
public void execute(@RequestParam String packageName, @RequestParam String prefix,
@RequestParam String modelName, @RequestParam String datasourceId,
@RequestParam String tableName, HttpServletRequest request,
HttpServletResponse response) {
SysDataSource sysDataSource = sysDataSourceService.getById(datasourceId);
String outputDir = System.getProperty("user.dir") + File.separator + "temp" + File.separator + "generator" + File.separator + UUID.randomUUID().toString();
CodeConfig config = new CodeConfig();
Expand All @@ -81,12 +87,9 @@ public Result<?> execute(@RequestParam String packageName, @RequestParam String
String[] srcDir = {outputDir + File.separator + (config.getPackageName().substring(0, config.getPackageName().indexOf(".")))};
try {
ZipUtil.toZip(srcDir, filePath, true);
FileUtil.download(filePath, fileName, true, response);
} catch (Exception e) {
log.error(e.getMessage());
}
Map data = Maps.newHashMap();
data.put("filePath", filePath);
data.put("fileName", fileName);
return Result.data(data);
}
}

0 comments on commit 53d36f7

Please sign in to comment.