项目需要做一个模板管理,由于模板内容不多,所以并不使用Nginx和FTP和OSS管理,采用最朴素的文件上传到本地服务器中。
Controller层
/**
* 上传模板到相对路径
*/
@Operation(tags = "文件模版表", summary = "上传模板到相对路径")
@PostMapping("/upload")
@ApiImplicitParams({
@ApiImplicitParam(name = "file", value = "文件"),
@ApiImplicitParam(name = "code", value = "文件code唯一")
})
public Result upload(MultipartFile file, String code){
return templateService.uploadTemplate(file, code);
}
/**
* 获取文件返回
*
* @param response
* @throws IOException
*/
@GetMapping(value = "file")
@ApiImplicitParams({
@ApiImplicitParam(name = "code", value = "文件code")
})
public void file(String code, HttpServletResponse response) throws IOException {
templateService.getFile(code, response);
}
Service
/**
* 上传模板到相对路径
* @param file
* @return
*/
Result uploadTemplate(MultipartFile file,String code);
/**
* 获取文件名
* @param code
* @param response
*/
void getFile(String code, HttpServletResponse response) throws IOException;
ServiceImpl
@Override
public Result uploadTemplate(MultipartFile file, String code) {
// 获取项目根目录
String property = null;
try {
property = new File(ResourceUtils.getURL("classpath:").getPath()).getParent();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 判断code是否已经存在
Template template = templateMapper.selectOne(Wrappers.lambdaQuery(Template.class)
.eq(Template::getDeleted, false)
.eq(Template::getCode, code));
if (Objects.nonNull(template)) {
throw new ApplicationException(500, code + "模板已存在");
}
// 获取文件后缀名
String substring = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
try {
//完成入库操作
Template build = Template.builder().code(code)
.name(file.getOriginalFilename())
.extension(substring)
.path( this.path + code + substring)
.build();
templateMapper.insert(build);
savePic(file.getInputStream(), code + substring, property + this.path);
} catch (IOException e) {
e.printStackTrace();
}
return Result.success();
}
@Override
public void getFile(String code, HttpServletResponse response) throws IOException {
String property = new File(ResourceUtils.getURL("classpath:").getPath()).getParent();
// 通过文件id查询模板文件
Template template = templateMapper.selectOne(Wrappers.lambdaQuery(Template.class)
.eq(Template :: getCode,code)
.eq(Template :: getDeleted ,false));
if (Objects.isNull(template)) {
throw new ApplicationException(500, "模板不存在");
}
// 读到流中
InputStream inStream;
try {
inStream = new FileInputStream(property + template.getPath());
// 设置输出的格式
response.reset();
response.setContentType("application/octet-stream");
String filename = URLEncoder.encode(template.getName(), StandardCharsets.UTF_8);
response.addHeader("Content-Disposition", "attachment; filename=" + filename);
// 循环取出流中的数据
byte[] b = new byte[100];
int len;
while ((len = inStream.read(b)) > 0) {
response.getOutputStream().write(b, 0, len);
}
inStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* 保存文件到指定目录
*
* @param inputStream 输入流
* @param code 文件code
*/
private void savePic(InputStream inputStream, String code, String property) {
// 获取项目根目录
OutputStream os = null;
try {
// 1K的数据缓冲
byte[] bs = new byte[1024];
int len;
// 输出的文件流保存到本地文件
File tempFile = new File(property);
if (!tempFile.exists()) {
tempFile.mkdirs();
}
// 用code保存文件名
os = new FileOutputStream(tempFile.getPath() + File.separator + code);
// 开始读取
while ((len = inputStream.read(bs)) != -1) {
os.write(bs, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 完毕,关闭所有链接
try {
assert os != null;
os.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}