Java下载文件的几种方式「建议收藏」

Java下载文件的几种方式「建议收藏」1.以流的方式下载.publicHttpServletResponsedownload(Stringpath,HttpServletResponseresponse){try{//path是指欲下载的文件的路径。Filefile=newFile(path);//取得文件名…

大家好,又见面了,我是你们的朋友全栈君。

1.以流的方式下载.

public HttpServletResponse download(String path, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }

2.下载本地文件

public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {
        // 下载本地文件
        String fileName = "Operator.doc".toString(); // 文件的默认保存名
        // 读到流中
        InputStream inStream = new FileInputStream("c:/Operator.doc");// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3.下载网络文件

public void downloadNet(HttpServletResponse response) throws MalformedURLException {
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;

        URL url = new URL("windine.blogdriver.com/logo.gif");

        try {
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream("c:/abc.gif");

            byte[] buffer = new byte[1204];
            int length;
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                System.out.println(bytesum);
                fs.write(buffer, 0, byteread);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

4.支持在线打开的方式

public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
        File f = new File(filePath);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;

        response.reset(); // 非常重要
        if (isOnLine) { // 在线打开方式
            URL u = new URL("file:///" + filePath);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
            // 文件名应该编码成UTF-8
        } else { // 纯下载方式
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
        }
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0)
            out.write(buf, 0, len);
        br.close();
        out.close();
    }

 

喜欢本文的朋友们,欢迎关注微信公众号“Java面试达人”,收看更多精彩内容

Java下载文件的几种方式「建议收藏」

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/156262.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • SQL Prompt10 安装激活教程,让你写sql 如鱼得水[通俗易懂]

    SQL Prompt10 安装激活教程,让你写sql 如鱼得水[通俗易懂]需要sql_Prompt10压缩包的请看文章最底下1.首先得有我们的SQLPrompt10压缩包2.选择SQLPromptDownload.exe进行安装打开安装界面,全部勾选选点击continue——–>>继续下一步点击accept选择安装位置,一般不推荐安装C盘,继续install——>>>>等待安装完成点击finish3.打开sqlserver数据库打开sqlserver数据库,可能有些兄弟进入不是这样得,有sql_

    2022年7月26日
    50
  • 6421B Lab1 规划和配置IPv4

    6421B Lab1 规划和配置IPv4

    2021年8月20日
    54
  • oracle怎么使用触发器,oracle触发器使用[通俗易懂]

    oracle怎么使用触发器,oracle触发器使用[通俗易懂]2)触发器分类:1.DML触发器:创建在表上,由DML事件引发2.insteadof触发器:创建在视图上并且只能在行级上触发,用于替代insert,delete等操作(由于oracle中不能直接对有两个以上的表建立的视图进行DML操作,所以给出替代触发器,它是专门为进行视图操作的一种处理方法)3.DDL触发器:触发事件时数据库对象的创建和修改4.数据库事件触发器:定义在数据库或者模式上,由…

    2022年7月11日
    15
  • 计算机专业的男生喜欢你,男生暗恋你的20个动作 一秒看出他喜欢你

    计算机专业的男生喜欢你,男生暗恋你的20个动作 一秒看出他喜欢你很多女生想知道是不是有男生在暗恋自己,下面小编为大家介绍一下男生暗恋你的20个动作。1、眼睛总是忍不住盯着那个女生。2、在女生的面前会表现得特别活跃。3、在女生开心的时候会很开心,在女生伤心的时候,心情就会像乌云密布的天空。4、如果那个女生和其他男生表现得很要好,就会忍不住要吃醋。5、如果那个女生心情低落,就会想过去安慰她。6、对于女生所拜托的事情,就算再难做也会答应。7、女生一上Q,就会很兴奋,…

    2022年7月25日
    38
  • PHP变量

    PHP变量

    2021年9月17日
    65
  • Opencv中width和widthStep的区别

    Opencv中width和widthStep的区别在Opencv的结构Iplimage中,widthStep并不一定等于width*nChannel*(数据类型所占字节),这是因为Opencv中对内存有管理的机制,这一机制会对内存进行对齐,也就是当每一行所占的字节数不等于4的倍数时会自动补齐。例如:width=117,depth=8U,nChannel=1,则widthStep=120,因为117不是4的倍数,所以补齐到120。如果dep

    2022年6月7日
    43

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号