java 下载文件

java 下载文件阅读原文1.以流的方式下载.publicHttpServletResponsedownload(Stringpath,HttpServletResponseresponse){try

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

阅读原文

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-Disposition", "attachment;filename=" +URLEncoder.encode(file.getName(),"utf-8"));

            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();






 /*response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, path));
            FileUtils.writeBytes(path, response.getOutputStream());*/





            /*File file = new File(path);
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(),"utf-8"));
            response.setContentType("application/octet-stream; charset=UTF-8");
            FileUtils.setAttachmentResponseHeader(response, URLEncoder.encode(file.getName(),"utf-8"));
            FileUtils.writeBytes(path, response.getOutputStream());
*/





        } 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();
    }

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

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

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


相关推荐

  • vb教程编程实例详解pdf_vb程序设计教程第五版答案

    vb教程编程实例详解pdf_vb程序设计教程第五版答案实验8-5编写一个能将任意两个文件的内容合并的程序,程序界面由读者由自由设计。解题,在窗体建立一个按钮控件,假定C盘已经有两个要合并的文件text1.dat和text2.dat,代码如下:PrivateSubCommand1_Click()DimcharAsByteOpen”C:\text1.dat”ForBinaryAs#1Open”…

    2022年10月6日
    4
  • bs和cs开发架构的详细解析区别_BS与CS架构区别

    bs和cs开发架构的详细解析区别_BS与CS架构区别目前开发的基本架构。一、CS结构—-Client/Server1、开发者需要编写两个端点,一个是客户端程序,一个是服务端程序。举例:QQ、360等等。2、需要再客户机安装客户端的部分。3、弊端:客户端的维护比较麻烦,机器只要一重装,就需要重新安装该软件,同时升级也比较麻烦。后期有了一个解决方案:对于升级,可以通过网络升级的形式完成。4、好处:客户端的出现,可以

    2022年10月16日
    4
  • ZendOptimizer怎么安装?Php网站打开显示乱码

    ZendOptimizer怎么安装?Php网站打开显示乱码

    2021年10月10日
    64
  • tcping 用法「建议收藏」

    tcping 用法「建议收藏」目录一、概述二、软件安装三、使用二、参考资料一、概述ping程序发送icmp包,用于检测网络连通性,如果主机禁ping,就没办法判断连通性了。tcping程序基于tcp协议,查看网络延迟及开放的端口信息。二、软件安装1、下载tcping工具(根据自身系统选择32位/64位)tcping程序有很多不同的贡献者,此处下载的是EliFulkerson开发的tcping2、安装tcping将下载的exe文件放到c:\windows\system32\目录下面(如果下载的是64位的要把文件

    2022年6月23日
    68
  • 从tracker上获取peer列表[通俗易懂]

    从tracker上获取peer列表[通俗易懂] 从torrent文件中得到了tracker列表后,接下来的工作就是获取peer列表.tracker使用http协议.客户端向服务器发送标准的GET请求,就可以得到这个列表.tracker返回的信息是bencode编码.向tracker发送的GET请求有如下一些参数:info_hash(必须):    torrent文件中info字段的sha1.torrent文件解析器中已经计算此值,保存在CTo

    2022年9月1日
    5
  • linux webstorm激活码2022【中文破解版】

    (linux webstorm激活码2022)本文适用于JetBrains家族所有ide,包括IntelliJidea,phpstorm,webstorm,pycharm,datagrip等。https://javaforall.net/100143.htmlIntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,上面是详细链接哦~4…

    2022年4月2日
    118

发表回复

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

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