hutool实现文件上传与下载

XML 复制代码
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.16</version>
        </dependency>

文件上传需要创建一个表

java 复制代码
@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<SysFileInfo> 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("文件下载失败");
        }
    }
复制代码
相关推荐
C+-C资深大佬5 小时前
Java 变量:从入门到精通
java·开发语言·python
Flittly5 小时前
【日常小问】Docker 部署 Nacos 2.4.3,Dubbo 3.3 连接 Config Service 失败排查
java·spring boot·dubbo
kuonyuma5 小时前
java之动态代理
java·开发语言
衔烛之龙15 小时前
Windows x64 构建 liboqs-java教程
java·windows·python
一路向北North6 小时前
Spring Security OAuth2.0(20):完善环境配置
java·后端·spring
Java面试题总结6 小时前
IntelliJ IDEA 从卡顿到起飞,只用改这些。。。
java·ide·intellij-idea
兰令水6 小时前
hot100【acm版】【2026.7.11/12打卡-java版本】
java·开发语言·数据结构·算法·职场和发展
Misnearch6 小时前
nacos配置管理改造
java·spring cloud·nacos
XWalnut6 小时前
LeetCode刷题 day29
java·算法·leetcode
4154116 小时前
MyBatis-Plus + PostGIS 实战(1.1):Geometry 字段在 Swagger 中的优雅展示
java·mybatis·postgis