栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间:发布时间: 百科书网 趣学号

Controller层:

	
    @PostMapping(value = "/upload")
    Object saveFile(@RequestParam("file") MultipartFile[] file) {
        return eventService.saveFile(file);
    }
    
	
    @PostMapping(value = "/download")
    Object getFiles(@RequestBody FileDTO fileDTO,
                    HttpServletResponse response) {
        return eventService.getFiles(fileDTO, response);
    }
    
	
    @PostMapping(value = "/showFile")
    Object getFile(@RequestBody EventIdDto eventId) {
        return eventService.showFile(eventId.getEventId());
    }

Service层:

	@Value("${system.file}")
    private String filePath; // 在yml文件中配置路径
	
    @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();
    }

    
    @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);
        if (!zip.exists()) {
            // 获取事件信息
            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;
    }

	
    @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 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");
    }
    
    
    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);
            }
        }
    }
    
    
    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);
    }
    
    
    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工具包,请自行下载依赖。

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/276428.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号