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


相关推荐

  • 前端权限导致的跳转出现404错误

    前端权限导致的跳转出现404错误问题:管理员与超级管理员访问编辑文章时出现,超管可以正常编辑,而管理员出现跳转404问题。解决:该问题花费快一天,首先以为是后端的权限配置有问题,将后端的权限重新配置,但都没有作用。无解。 后来发现是前端配置了响应的权限导致的。先模仿着原有代码将问题解决了。 前端不是很清楚,后面有时间再琢磨个人博客地址:http://ganshuo8.com/…

    2022年6月13日
  • Spark Streaming Join「建议收藏」

    Spark Streaming Join「建议收藏」多数据源Join思路多数据源Join大致有以下三种思路:数据源端Join,如Android/IOS客户端在上报用户行为数据时就获取并带上用户基础信息。计算引擎上Join,如用SparkStreaming、Flink做Join。结果端Join,如用HBase/ES做Join,Join键做Rowkey/_id,各字段分别写入列簇、列或field。三种思路各有优劣,使用时注意…

    2022年6月30日
  • SLAM机器人开发(二)SLAM技术现状

    SLAM机器人开发(二)SLAM技术现状SLAM机器人开发(二)SLAM技术现状激光SLAM2D激光SLAM3D激光SLAM视觉SLAM常见的视觉SLAM视觉SLAM对比视觉SLAM中使用的相机种类视觉SLAM效果图视觉激光融合SLAM激光SLAM2D激光SLAM激光SLAM在SLAM技术中是较为传统且成熟的。2D激光SLAM技术需要输入IMU数据、里程计数据和2D激光雷达数据,经过计算后输出覆盖栅格地图和机器人轨迹。从20世纪90年代EKF-SLAM的提出开始,陆续出现了UKF-SLAM、PF-S

    2022年10月1日
  • 最常用三极管导通电路

    最常用三极管导通电路

    2022年6月15日
  • springcloudfeign原理和流程_ribbon和feign实现负载均衡的原理

    springcloudfeign原理和流程_ribbon和feign实现负载均衡的原理什么是Feign?Feign是一个http请求调用的轻量级框架,可以以Java接口注解的方式调用Http请求,而不用像Java中通过封装HTTP请求报文的方式直接调用。Feign通过处理注解,将请求模板化,当实际调用的时候,传入参数,根据参数再应用到请求上,进而转化成真正的请求,这种请求相对而言比较直观。Feign支持文本方式下的调用。Feign解决了什么问题?封装了Http调用流程,更…

    2022年10月4日
  • docker搭建真机的kafka集群

    docker搭建真机的kafka集群

    2021年8月3日

发表回复

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

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