每一年都奔走在自己热爱里 没有人是一座孤岛,总有谁爱着你

岁
万
月
12

文件下载与上传

项目地址:https://gitee.com/libeimaningg/beizhilib

(一)文件下载

Controller层:

    /**
     * 下载模板
     *
     * @param response
     */
    @PostMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        sysUserService.downloadTemplate(response);
    }

业务层:

    @Override
    public void downloadTemplate(HttpServletResponse response) {
        if (!FileUtil.exist(templatePath)) {
            FileUtil.mkdir(templatePath);
        }
        try (OutputStream os = response.getOutputStream();
             InputStream is = new FileInputStream(templatePath + "/" + "用户信息导入模板.xlsx")) {
            response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode("用户信息导入模板.xlsx", StandardCharsets.UTF_8));
            IOUtils.copy(is, os);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

(二)文件上传

Controller层:

    @PostMapping("/saveFile")
    public void saveFile(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
        sysUserService.saveFile(file, response);
    }

实现层:

    @Override
    public void saveFile(MultipartFile file, HttpServletResponse response) {
        //1.检查文件是否为空
        if (file.isEmpty()) {
            throw new BusinessException(StstusEnums.FAIL, BusinessEnums.FAIL.getType(), "文件不能为空");
        }
        //获取文件名:测试&运维_《员工申请表模板》.xlsx
        String filename = file.getOriginalFilename();
        //2.检查文件名是否为空或者空字符串
        if (filename == null || filename.trim().isEmpty()) {
            throw new BusinessException(StstusEnums.FAIL, BusinessEnums.FAIL.getType(), "文件名不能为空或者空字符串");
        }
        //3.(可选) 检查文件大小: 数字 10485760 等于10 * 1024 * 1024, 也就是 10MB 的字节大小:196962
        long fileSize = file.getSize();
        if (fileSize > 10485760) {
            throw new BusinessException(StstusEnums.FAIL, BusinessEnums.FAIL.getType(), "文件过大");
        }
        //4.(可选) 检查文件类型:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
        String contentType = file.getContentType();
//        if (!("image/png".equals(contentType) || "image/jpeg".equals(contentType))) {
//            throw new BusinessException(StstusEnums.FAIL, BusinessEnums.FAIL.getType(), "文件不能为空");
//        }

        UUID uuid = UUID.randomUUID();
        try {
            if (!FileUtil.exist(filePath)) {
                FileUtil.mkdir(filePath);
                log.info("创建文件夹成功:" + filePath);
            }
//            FileUtil.writeFromStream(file.getInputStream(), filePath + "/" + uuid.toString() + filename);//方法一
            file.transferTo(new File(filePath + "/" + uuid.toString() + filename));//方法二
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
posted @ 2025-03-12 19:37  果咩那塞  阅读(4)  评论(0)    收藏  举报