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

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 附件
     **/
    @Override
    public 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 文件下载路径
     **/
    @Override
    public 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
     **/
    @Override
    public 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工具包,请自行下载依赖。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值