文件下载

文件下载

注意文件下载时直接window.location.href=""即可,如果需要异步前端还需要再处理一番

public void download(String filePath,String OriginalFilename){
        InputStream fis=null;
        OutputStream toClient=null;
        try {
            //获取下载的路径
            File file=new File(filePath);
            //获取文件名,该方法是下载图片时换上原来的名字,存在文件里面的名字是随机数
            String filename=OriginalFilename;
            //取得文件的后缀名
            String ext=filename.substring(filename.lastIndexOf(".")+1).toUpperCase();
            //以流的形式下载文件
            fis=new BufferedInputStream(new FileInputStream(file));
            System.out.println("文件大小:"+fis.available());
            //创建一个和文件一样大小的缓存区
            byte[] buffer=new byte[fis.available()];
            //读取流
            fis.read(buffer);
            //清空首部空白行
            response.reset();
            //设置文件下载后的指定文件名
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("gb2312"),"ISO8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            //response.getOutputStream() 获得字节流,通过该字节流的write(byte[] bytes)可以向response缓冲区中写入字节,再由Tomcat服务器将字节内容组成Http响应返回给浏览器。
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            //将buffer 个字节从指定的 byte 数组写入此输出流。
            toClient.write(buffer);
            //刷新此缓冲的输出流。这迫使所有缓冲的输出字节被写出到底层输出流中。 把缓存区的数据全部写出
            toClient.flush();
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            try {
                //关闭流
                fis.close();
                //关闭缓冲输出流
                toClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
}        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值