springboot实现文件的上传和下载

1.实现文件的上传

1.1controller

这段代码最主要的就是需要一个用请求体接受一个MultipartFile,上面的其他请求参数这里可以不要。

1.2创建一个方法来处理MultipartFile

 public static Object uploadFile(HttpServletResponse response, MultipartFile file){
        if (file.isEmpty()){
            throw new RuntimeException("文件不能为空");
        }
        //获得想要输出的文件路径(后面的意思是每天产生一个文件夹)
        String path="D:\\file"+DateUtil.getTodayDirectoryPath();
        //判断这个文件夹是否存在
        if (!new File(path).exists()){
            //如果不存在,就创建一个
            new File(path).mkdirs();
        }
        //执行写入操作
        try {
            file.transferTo(new File(path+"\\"+file.getOriginalFilename()));
            return path+"\\"+file.getOriginalFilename();
        } catch (IOException e) {
            throw new RuntimeException("上传失败");
        }
    }

这里面主要的就是先创建一个文件夹,为了方便管理和查看,我这里会按照日期每天生成一个,这个工具类如下

public class DateUtil {
    /**
     * 立即获取当前完整日期
     *
     * @return {@link String }
     * @time 2023/11/30--05:30:07
     **/
    public static String getCompleteNowDate() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    /**
     * 获得当天的时间
     *
     * @return {@link String }
     * @time 2023/12/08--10:40:38
     * @Exception
     **/
    public static String getDay(){
        return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    }

    /**
     * 获取今天目录路径
     *
     * @return {@link String }
     * @time 2023/12/08--10:40:55
     * @Exception
     **/
    public static String getTodayDirectoryPath(){
        return new SimpleDateFormat("\\yyyy\\MM\\dd").format(new Date());
    }
}

然后使用transferTo的方法写入具体的文件夹

2实现文件的下载

 /**
     * 下载文件(以流的方式)
     *
     * @param response 回答
     * @param path     路径
     * @time 2023/12/08--04:51:00
     * @Exception @throws UnsupportedEncodingException 不支持编码异常
     **/
    public static void downloadFile(HttpServletResponse response, String path) throws IOException {
        //拿到真实的文件的路径
        File file = new File(path);
        if (!file.exists()) {
            throw new RuntimeException("文件不存在");
        }
        //设置文件名
        String fileName = file.getName();
        //设置文件类型
        String type = fileName.substring(fileName.lastIndexOf(".") + 1);
        //设置文件大小
        long size = file.length();
        //设置响应头
        response.setContentType("application/octet-stream");
        //这里设置URLEncoder是为了防止文件里面有中文名,防止解析异常
        response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(file.getName()+"."+type, "UTF-8"));
        //把文件以流的形式写入响应
        //获得文件输入流
        FileInputStream fileInputStream = new FileInputStream(file);
        //把获得文件输入流的字节数组,在文件大小较大的时候,下面的数字越大速度会更快一些
        byte[] bytes = new byte[4096];
        //这个返回的结果当为-1的时候就代表文件读到末尾了
        int length;
        while ((length=fileInputStream.read(bytes))!=-1){
            //把字节数组写入响应输出流
            response.getOutputStream().write(bytes,0,length);
        }
        // 刷新输出流
        response.getOutputStream().flush();
    }

1.首先这个方法需要两个参数一个就是请求的响应HttpServletResponse还有一个文件的路径

2.拿到这两个后先根据路径拿到文件。

3把文件转换成文件输入流。

4.再把文件输入流转换成为字节数组

5.得到响应的输出流

6.把字节数组写入响应的输出流就大功告成了。

  • 18
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值