XML
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
文件上传需要创建一个表
java
@Autowired
private SysFileInfoMapper sysFileInfoMapper;
@Value("${ty.profile}")
private String profile;
@PostMapping("/add")
public AjaxResult addSave( MultipartFile file, SysFileInfo fileInfo) throws IOException
{
//获取文件名2.txt
String originalFilename = file.getOriginalFilename();
//给文件名添加前缀年月日时分秒毫秒,防止文件名称重复给顶掉
String fileName = DateUtils.parseDateToStr("yyyyMMddHHmmssSSS", DateUtils.getNowDate()) +"_"+ originalFilename;
//获取文件路径,主路径+文件名
String path = profile+"/"+fileName;
//使用huTool工具类实现文件上传
FileUtil.writeBytes(file.getBytes(),path);
//将文件名和文件路径存入表中
fileInfo.setFileName(fileName);
fileInfo.setFilePath(path);
sysFileInfoMapper.insert(fileInfo);
return AjaxResult.success("成功");
}
/**
* 本地资源通用下载
*/
@GetMapping("/common/download/resources")
public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
throws Exception
{
try {
ServletOutputStream outputStream = response.getOutputStream();
//根据文件名称查询文件路径
LambdaQueryWrapper<SysFileInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
lambdaQueryWrapper.eq(SysFileInfo::getFileName,resource);
SysFileInfo sysFileInfo = sysFileInfoMapper.selectOne(lambdaQueryWrapper);
if (ObjectUtil.isNotNull(sysFileInfo)){
String filePath = sysFileInfo.getFilePath();
response.setCharacterEncoding("utf-8");
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(sysFileInfo.getFileName(), "UTF-8"));
response.setContentType("application/octet-stream");
//通过文件的路径读取文件字节流,通过response的输出流返回文件
outputStream.write(FileUtil.readBytes(filePath));
outputStream.flush();
outputStream.close();
}
}catch (Exception e){
throw new SecurityException("文件下载失败");
}
}