java/springboot 实现本地资源下载

上代码

具体逻辑都在代码注释中体现!

  @GetMapping("/downModel")
    public AjaxResult downModel(HttpServletResponse response) {
        //本地资源路径
        String path = "";
        //文件名
        String fileName = "";
        //创建文件对象
        File file = new File(path);
        if(!file.exists()){
            return AjaxResult.error("文件下载失败,请联系管理员!");
        }
        // 设置媒体类型为二进制流,不知道下载文件类型时使用
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); //"application/octet-stream"
        //此报文头content-disposition,对报文体进行描述,规定了接收端的显示处理行为。 
        response.setHeader("Content-Disposition", "attachment;filename="+fileName);
        //创建输入流,用于读取本地文件
        InputStream is = null;
        try{
            is = new FileInputStream(file);
            //is输入流的内容copy到输出流。内部源码下面会介绍,很简单的
            IOUtils.copy(is,response.getOutputStream());
            //Flushes this output stream and forces any buffered output bytes to be written out.
            //正如上所说刷新此输出流,强制写出
            response.getOutputStream().flush();
        }catch (Exception e){
            return AjaxResult.error("文件下载失败,请联系管理员!");
        }finally {
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

IOUtils.copy源码

本质上就是跟将输入流转为输出流。buffer为缓冲区

	//buffer 默认大小 1024*4
    public static long copyLarge(final InputStream input, final OutputStream output, final byte[] buffer)
            throws IOException {
        long count = 0;
        int n;
        // EOF = -1,
        // 当input(输入流)读到末尾时,返回-1.所以不等于-1的还要继续读,并且转换为output(输出流)
        while (EOF != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }

前端代码

很简单使用a标签指明后端路径就好

<a href = "url" />
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值