用户浏览器点击按钮下载文件,java后台代码

本文介绍两种文件下载的方法,一种直接读取文件到内存再下载,另一种采用缓冲区逐块读取,后者更适用于大文件下载,避免内存溢出,提高性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:用户点击下载按钮,将本地文件响应给用户

方法一:
//controller 层
@RequestMapping("/testDownloadFile.do")
    public void testDownloadFile(HttpServletResponse response){
        InputStream inputStream=null;
        try {
            File file = new File("E:\\others\\fileTest.txt");
            inputStream=new FileInputStream(file);
            GetClient.fileDownload(file.getName(),inputStream,response);
        }catch (Exception e){
        	e.printStackTrace();
            log.error("出现异常了,请稍后重试");
        }
    }

//文件下载方法,可以防止util中
public static void fileDownload(String filename, InputStream input, HttpServletResponse response){
    try {
        byte[] buffer = new byte[input.available()];
        input.read(buffer);
        input.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        //关闭,即下载
        toClient.close();
    }catch (Exception e){
        e.printStackTrace();
    }
}

测试:
在这里插入图片描述

测试:正常下载,通过!

方法二:
//controller 层
@RequestMapping("/testDownloadFile.do")
    public void testDownloadFile(HttpServletResponse response){
        InputStream inputStream=null;
        try {
            File file = new File("E:\\others\\fileTest.txt");
            inputStream=new FileInputStream(file);
            GetClient.fileDownload(file.getName(),inputStream,response);
        }catch (Exception e){
        	e.printStackTrace();
            log.error("出现异常了,请稍后重试");
        }
    }

//文件下载方法,可以防止util中
public static void fileDownload(String filename, InputStream input, HttpServletResponse response){
    try {
       byte[] buffer = new byte[4096];
        int readLength = 0;
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        while ((readLength=input.read(buffer)) > 0) {
            byte[] bytes = new byte[readLength];
            System.arraycopy(buffer, 0, bytes, 0, readLength);
            toClient.write(bytes);
        }
        input.close();
        toClient.flush();
        toClient.close();
    }catch (Exception e){
        e.printStackTrace();
    }
}

在这里插入图片描述

测试:正常下载,通过!
总结

方法二在方法一的基础上进行了优化,在实现功能的基础上考虑了性能。从上面代码可以看出,方法一在大文件下载时会占用很多内存资源,多个用户同时下载大文件会存在宕机的隐患 。实际项目中该功能是从分布式文件存储系统上下载文件响应给用户,本例进行了简化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值