<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.16</version></dependency>
文件上传需要创建一个表
@Autowiredprivate SysFileInfoMapper sysFileInfoMapper;@Value("${ty.profile}")private String profile;@PostMapping("/add")public AjaxResult addSave( MultipartFile file, SysFileInfo fileInfo) throws IOException{//获取文件名2.txtString 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("文件下载失败");}}