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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 少儿编程的学习[通俗易懂]

    少儿编程第一课1.软件的认识2.顶部工具栏的认识3.认识背景,角色,舞台区,以及他们的分别上传4.代码库和代码编辑区第一课1.软件的认识Scratch是由MIT(美国麻省理工学院)针对5至16岁的儿童和青少年设计的可视化程序设计语言与开发环境,专注于用编程实现简单的动画效果。相比其他传统的编程语言,例如VB,Java,Pascal等相比,Scratch语言创建的目的不是为了培养少年程序员…

    2022年4月7日
    42
  • 前端页面图片加载失败显示默认图片

    前端页面图片加载失败显示默认图片方法有多种:1.首先说我用的,看代码//页面图片加载失败时默认显示统一处理document.addEventListener("error",function(e){  varelem=e.target;  if(elem.tagName.toLowerCase()=="img"){    elem.src="/image/General/errorDef…

    2022年6月2日
    37
  • TOP命令详解(TOP10)

    原文http://rockhooray.blog.51cto.com/938613/832621一概述在终端中可以查看top命令的路径和所属软件包。top程序对运行的系统提供一个动态的实时的监控。它能够显示系统的总体信息和一些正被Linux内核管理的任务。它所显示的系统总体信息的样式以及任务信息显示的样式,顺序和大小都是可以由用户配置,而且配置信息可以重启后永久生

    2022年4月11日
    238
  • 电脑WindowsUDP53绕过校园网认证登陆(同时可进内外网教程)

    电脑WindowsUDP53绕过校园网认证登陆(同时可进内外网教程)管理员命令行输入:routeadd-p172.16.0.0mask255.255.0.0172.16.180.254加粗的两个改成你自己的,第二个加粗是默认网关!第一个不知怎么叫。。仔

    2025年6月12日
    3
  • 神经网络的基本原理[通俗易懂]

    神经网络的基本原理[通俗易懂]1.神经网络1.1.神经元概述神经网络是由一个个的被称为“神经元”的基本单元构成,单个神经元的结构如下图所示:对于上述的神经元,其输入为x1x_1x1​,x2x_2x2​,x3x_3x3​以及截距+1+1+1,其输出为:hW,b(x)=f(WTx)=f(∑i=13Wixi+b)h_{\mathbf{W},b}\left(\mathbf{x}\right)=f\left(\mathbf{W}^T\mathbf{x}\right)=f\left(\sum_{i=1}^{3}W_

    2022年7月20日
    12
  • linux负载高但cpu使用率低_cpu工作负载

    linux负载高但cpu使用率低_cpu工作负载文章目录前言什么是系统平均负载?一个类比多处理器和多核系统CPU使用率注意输入/输出(I/O)操作一些技巧前言做为一个性能测试工程师,每当我们发现计算机变慢的时候,我们通常的标准姿势就是执行uptime或top命令,来了解系统的负载情况。比如像下面这样,我在命令行里输入了uptime命令,系统会返回一行信息。appletekimbp:~apple$uptime20:4…

    2025年11月2日
    3

发表回复

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

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