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("文件下载失败");
        }
    }
复制代码
相关推荐
笨手笨脚の9 分钟前
设计模式-迭代器模式
java·设计模式·迭代器模式·行为型设计模式
spencer_tseng1 小时前
Eclipse 4.7 ADT (Android Development Tools For Eclipse)
android·java·eclipse
聪明的笨猪猪1 小时前
Java Spring “AOP” 面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试
seven97_top3 小时前
Springboot 常见面试题汇总
java·spring boot·后端
小蕾Java3 小时前
Java 开发工具,最新2025 IDEA 使用,保姆级教程
java·开发语言·intellij-idea
刘登辉3 小时前
idea使用联网缓存的pom进行离线开发
java·ide·intellij-idea·离线开发
Автомата Калашникова3 小时前
Java操作.docx文档 —— docx4j
java·开发语言
hello 早上好3 小时前
深入 Spring 条件化配置底层:从硬编码到通用注解的实现原理
java·后端·spring
亚林瓜子3 小时前
Spring中Date日期序列化与反序列化中格式设置
java·后端·spring·jackson·date
GISer_Jing3 小时前
Next.js数据获取演进史
java·开发语言·javascript