文件下载的4种方式

news/2024/7/2 3:19:00

转自:https://www.cnblogs.com/sunny3096/p/8204291.html

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

 


http://www.niftyadmin.cn/n/3152730.html

相关文章

学习bash第二版-附录四 语法

**保留字 下面关键字为保留字,在它们没有被引起来时对shell具有特殊的含义: if then else elif fi case esac for while until do done function in select ! { } time **bash的BNF 以下为bash 2.0的Backus-Naur Form(BNF…

hdu折线分割平面 递推

折线分割平面 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 37707 Accepted Submission(s): 25240Problem Description 我们看到过很多直线分割平面的题目,今天的这个题目稍微有些变化&#xff0…

这是我们公司总结的一些关于中文乱码问题的一些解决方案和经验和大家分享!

这是我们公司总结的一些关于中文乱码问题的一些解决方案和经验和大家分享! owen1944 原创 (参与分:208,专家分:760) 发表:2003-7-28 下午10:04 版本:1.0 阅读:3762 次 1.字节和unicode …

学习bash第二版-附录五 获得示例程序

可通过FTP和FTPMAIL方式得到本书的一些例子。如果连接了Internet,可使用FTP。如果未连接Internet但可以发送并接收电子邮件到Internet站点上,可使用FTPMAIL。 **FTP 如果你具有Internet连接(永久或拨号),最简单的…

response.setContentType()与response.setHeader()

1、一秒刷新页面一次 response.setHeader("refresh","1"); 2、二秒跳到其他页面 response.setHeader("refresh","2;URLotherPagename"); 3、没有缓存: response.setHeader("Pragma", "No-cache"); r…

ejb3.0 数据源配制

1. 首先在JBOSS的\server\default\deploy目录下建立XML文档&#xff0c;此文档的名称一般根据所使用的数据库而定&#xff0c;如mysql的为mysql-ds.xml &#xff0c;db2的为db2-ds.xml。文档的内容一般如下&#xff1a;<?xml version"1.0" encoding"U…

git仓库的bare方式

git提供一种对外发布&#xff0c;供开发者克隆的一种空工作目录的bare方式。这种方式的优点在于节省存储空间。 1.要从头开始创建bare方式的git仓库&#xff0c;步骤如下&#xff1a; 注&#xff1a;假定要创建的git仓库位于/home/chen/sw目录&#xff0c;源文件位于/home/zh…

git最新版本2.19.1出现fatal: NullReferenceException encountered解决方案

git最新版本2.19.1在提交新的版本时会出现如下图所示异常&#xff1a; 此问题不影响代码的pull与push及clone&#xff0c;但是会出现上述错误。 是因为git的credential manager 在版本2.19.1会出现问题。为此可以在如下链接下载&#xff1a; https://github.com/Microsoft/Gi…