- <dependency>
- <groupId>cn.hutoolgroupId>
- <artifactId>hutool-allartifactId>
- <version>5.8.16version>
- dependency>
文件上传需要创建一个表
- @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
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("文件下载失败");
- }
- }
-
-
- //实现pdf预览
- @GetMapping("/getPdfView")
- public void pdf(HttpServletRequest request, HttpServletResponse response) {
- try {
- File file = new File("C:\\hzx\\uploadPath\\2023\\10\\12\\打车去高铁站发票_20231012112938A001.pdf");
- FileInputStream fileInputStream = new FileInputStream(file);
- response.setHeader("Content-Type", "application/pdf");
- OutputStream outputStream = response.getOutputStream();
- IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
- } catch(Exception e) {
- e.printStackTrace();
- }
- }