Controller层:

 /*** 保存附件按钮* @param file 附件* @return 附件路径**/@PostMapping(value = "/upload")Object saveFile(@RequestParam("file") MultipartFile[] file) {return eventService.saveFile(file);}/*** 下载附件按钮* @param fileDTO 事件id和文件路径* eventId 事件id* downloadPath 下载的压缩包名* @return 附件**/@PostMapping(value = "/download")Object getFiles(@RequestBody FileDTO fileDTO,HttpServletResponse response) {return eventService.getFiles(fileDTO, response);}/*** 查看附件* @param eventId 事件id* @return 列表**/@PostMapping(value = "/showFile")Object getFile(@RequestBody EventIdDto eventId) {return eventService.showFile(eventId.getEventId());}

Service层:

 @Value("${system.file}")private String filePath; // 在yml文件中配置路径/*** 保存附件按钮* @return 附件路径* @param file 附件**/@Overridepublic String saveFile(MultipartFile[] files) {StringBuilder filesPath = new StringBuilder();if (files == null) {throw new CustomException("附件不能为空");}try {for (MultipartFile file : files) {//上传文件int idx = file.getOriginalFilename().indexOf('.');String ext = file.getOriginalFilename().substring(idx + 1);String fileName = UUID.randomUUID().toString().replace("-", "") + "." + ext;FileIoUtil.fileUpload(file, filePath, fileName);filesPath.append(filePath + fileName).append(",");}filesPath.delete(filesPath.lastIndexOf(","), filesPath.lastIndexOf(",") + 1);} catch (IOException e) {e.printStackTrace();}return filesPath.toString();}/*** 下载附件按钮** @return 附件路径* @param userId 用户Id* @param eventId 事件Id* @param downloadPath 文件下载路径**/@Overridepublic Object getFiles(FileDTO fileDTO, HttpServletResponse response) {String eventId = fileDTO.getEventId();String downloadPath = fileDTO.getDownloadPath();if (StringUtils.isBlank(eventId)) {throw new CustomException("事件id不能为空");}int index = downloadPath.lastIndexOf("/");String fileName = downloadPath.substring(index + 1, downloadPath.length());File zip = new File(filePath + fileName);// 获取事件信息Event event = eventMapper.selectByPrimaryKey(eventId);if (event == null) {throw new CustomException("未找到对应的事件信息");}if (StringUtils.isBlank(event.getFileLocation())) {throw new CustomException("文件不存在");}// 获取文件路径String[] filesPath = event.getFileLocation().split(",");File[] files = new File[filesPath.length];// 压缩文件for (int i = 0; i < filesPath.length; i++) {File file = new File(filesPath[i]);files[i] = file;}ZipUtil.zip(FileUtil.file(filePath + fileName), false, files);// 传输文件ServletOutputStream out = null;FileInputStream is = null;try {response.setCharacterEncoding("UTF-8");response.setContentType("text/html");response.setHeader("Content-Disposition", "attachment;fileName=" + downloadPath);is = new FileInputStream(zip);out = response.getOutputStream();int b = 0;byte[] buffer = new byte[1024];while ((b = is.read(buffer)) != -1) {out.write(buffer, 0, b);}} catch (IOException e) {e.printStackTrace();} finally {try {if (is != null) {is.close();}if (out != null) {out.close();}} catch (IOException e) {e.printStackTrace();}}return null;}/*** 查看报告* @return 结果* @param eventId 用户id**/@Overridepublic Object showFile(String eventId) {if (StringUtils.isBlank(eventId)) {throw new CustomException("事件id不能为空");}Event event = eventMapper.selectByPrimaryKey(eventId);if (event == null) {throw new CustomException("未找到对应的事件信息");}// 获取文件路径String[] filesPath = event.getFileLocation().split(",");List<String> list = new ArrayList<>();BufferedReader reader = null;try {for (String path : filesPath) {File file = new File(path);reader = new BufferedReader(new FileReader(file));StringBuffer sbf = new StringBuffer();String tempStr;while ((tempStr = reader.readLine()) != null) {sbf.append(tempStr);}list.add(sbf.toString());}} catch (Exception e) {e.printStackTrace();}return list;}

FileIoUtil:

public class FileIoUtil {private FileIoUtil() {throw new IllegalStateException("Utility class");}/*** 文件上传** @param file     文件* @param path     文件存放路径* @param fileName 文件名* @throws IOException "file empty"*/public static void fileUpload(MultipartFile file, String path, String fileName) throws IOException {if (file.isEmpty()) {throw new IOException("file empty");}String filePath = path + fileName;try (InputStream in = file.getInputStream();FileOutputStream out = new FileOutputStream(filePath)) {int count;while ((count = in.read()) != -1) {out.write(count);}}}/*** 文件上传** @param file 文件* @param path 文件存放路径* @throws IOException "file empty"*/public static void fileUpload(MultipartFile file, String path) throws IOException {if (file.isEmpty()) {throw new IOException("file empty");}String fileName = file.getOriginalFilename();fileUpload(file, path, fileName);}/*** 文件下载** @param fileName 文件名* @param filePath 文件存放路径* @param response HttpServletResponse* @throws IOException "file not exists"*/public static void fileDownload(String fileName, String filePath, HttpServletResponse response) throws IOException {String path = filePath + fileName;File file = new File(path);if (!file.exists()) {throw new IOException("file not exists");}try (OutputStream out = response.getOutputStream();FileInputStream in = new FileInputStream(path)) {response.reset();response.setContentType("application/octet-stream; charset=utf-8");response.setCharacterEncoding("utf-8");response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));int count;byte[] buffer = new byte[1024];while ((count = in.read(buffer)) > 0) {out.write(buffer, 0, count);}}}
}

ZipUtils使用了Hutool工具包,请自行下载依赖。

Springboot前后端分离上传、下载压缩包、查看文件相关推荐

  1. 使用nginx反向代理做前后端分离 上传大文件速度特别慢

    出现的问题 环境 VUE+JAVA 问题描述 在本地上传100MB+的文件速度特别快,基本上十几秒钟可以上传结束 但是上传到服务器后,需要5分钟以上,服务器带宽10MB(阿里云) 检查结果 经过多次检 ...

  2. 基于SpringBoot前后端分离的众筹系统(附源码)

    基于SpringBoot前后端分离的众筹系统源码下载链接: https://download.csdn.net/download/weixin_47367099/85441573 一.运行步骤 1.环 ...

  3. Android+SpringBoot前后端分离实现登录注册

    Android+SpringBoot前后端分离实现登录注册 一.登录 1.界面设计 2.Android端 (1)布局文件(activity_login) (2)java文件(LoginActivity ...

  4. springboot前后端分离后权限原理浅谈

    1. 需求描述 最近在梳理springboot前后端分离后的权限管理问题.前段时间,已经把shiro的实现和spring security 的实现进行了初步的了解.如果深入细节,一个篇幅怕是不够.本文 ...

  5. SpringBoot后台管理+Uniapp(混合APP)前端 之 酒店住宿+景点下单管理系统(SpringBoot前后端分离)

    酒店住宿+景点下单管理系统(SpringBoot前后端分离) 之 SpringBoot后台管理+Uniapp(混合APP)前端 SpringBoot前后端分离项目-Thymeleaf模板引擎景区旅游管 ...

  6. 新手摸爬滚打:vue+springboot前后端分离项目演示(三)——axios实现前后端交互

    导语:路漫漫其修远兮,吾将上下而求索 前篇: 新手摸爬滚打:vue+springboot前后端分离项目演示(一)--vue cli创建vue2项目 新手摸爬滚打:vue+springboot前后端分离 ...

  7. SpringBoot前后端分离项目中如何制作前端jar包(类似swaggerUI前端jar包制作方法)

    SpringBoot前后端分离项目中如何制作前端jar包(类似swaggerUI前端jar包制作方法) 可用于SpringBoot引用的前端UI的Jar包,类似于SwaggerUI包 WABJAR介绍 ...

  8. B站云E办Vue+SpringBoot前后端分离项目——MVC三层架构搭建后台项目

    本项目来源B站云E办,笔记整理了项目搭建的过程和涉及的知识点.对于学习来说,不是复制粘贴代码即可,要知其然知其所以然.希望我的笔记能为大家提供思路,也欢迎各位伙伴的指正. 项目前端学习笔记目录 B站云 ...

  9. 基于vue springboot 前后端分离的电影院会员管理系统

    基于vue springboot 前后端分离的电影院会员管理系统 文章目录 基于vue springboot 前后端分离的电影院会员管理系统 前言 一.主要功能 二.运行截图 1.前端package. ...

最新文章

  1. CSS之布局(行内元素的盒模型)
  2. k8s traefik ingress tls
  3. Cf Round #403 B. The Meeting Place Cannot Be Changed(二分答案)
  4. java-Transient关键字、Volatile关键字介绍和序列化、反序列化机制、单例类序列化
  5. 建造SAP Fiori部署
  6. 用汇编语言写的第一个DOS程序
  7. thinkphp Hook行为的使用案例
  8. 分析了 200w 行 OpenHarmony 2.0 源码后,有了这些发现
  9. android ble 大小,Android BLE中传输数据的最大长度怎么破
  10. (C/C++学习笔记)附页: C/C++变量的存储类型
  11. 31部黑客电影,你看过哪几部?
  12. [RTOS]--uCOS、FreeRTOS、RTThread、RTX等RTOS的对比之特点
  13. 这个开源高仿某易云音乐项目,太酷了
  14. Flink SQL Size of the state is larger than the maximum permitted memory-backed state
  15. Source Insight 4.0.0086 Patched
  16. 排列显示阿拉伯语、数字及英文时的处理方法
  17. 连续函数的最佳平方逼近
  18. 我这样写python代码表白泡到了我的女神师姐
  19. potplayer播放完毕后自动删除播放记录,不保留近期播放记录
  20. 移动SLAM从入门到入土(二)环境安装

热门文章

  1. Go 学习笔记(82)— Go 第三方库之 viper(解析配置文件、热更新配置文件)
  2. libACE-6.3.3.so: cannot open shared object file: No such file or directory
  3. 2022-2028年中国增光膜行业市场研究及未来发展潜力报告
  4. 2022-2028年中国氟橡胶密封件行业市场研究及前瞻分析报告
  5. Go 学习笔记(62)— Go 中 switch 语句中的 switch 表达式和 case 表达式之间的关系
  6. PyTorch学习之六个学习率调整策略
  7. pytorch方法,Tensor及其基本操作_重点
  8. Nignx集成fastDFS后访问Nginx一直在加载中解决
  9. LeetCode简单题之找出数组排序后的目标下标
  10. 全文翻译(四) TVM An Automated End-to-End Optimizing Compiler