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


相关推荐

  • nv12转rgb「建议收藏」

    nv12转rgb「建议收藏」nv12格式nv12转rgb两种格式代码voidNV12_T_RGB(unsignedintwidth,unsignedintheight,unsignedchar*Y,unsignedchar*UV,unsignedchar*rgb){ intr,g,b; inty,u,v; for(inti=0;i<height;i++){ for(intj=0;j<width;j++){ y=

    2022年9月25日
    0
  • Windows 10配置远程开机[通俗易懂]

    Windows 10配置远程开机[通俗易懂]简介最近有个需求,在外边或者是上班的时候想从家里的电脑拿点资料,虽然家里的路由器有公网IP地址,但是电脑总不能一直开着吧,然后就想到可以远程通过网卡唤醒电脑。前提条件拥有一个公网IP(一般可以找运营商申请),如果拥有的公网IP是动态的话,需要绑定DDNS域名,DDNS域名可以自行注册。 电脑主板支持网络唤醒功能。配置方法主板开启网络唤醒功能,如图:设置网络适配器支持唤醒…

    2022年5月5日
    159
  • Ubuntu命令备忘

    Ubuntu命令备忘

    2021年7月29日
    51
  • js layui 弹出子窗体_Layui弹出层 加载 做编辑页面的方法[通俗易懂]

    js layui 弹出子窗体_Layui弹出层 加载 做编辑页面的方法[通俗易懂]layui是一款优秀的模块化前端框架。利用layui弹出层做编辑页面先上效果图基本准备,引入layui的layui.css,layui.js文件Js方法/***页面内弹出编辑窗口//需要引入layui.jslayui.css文件*@param{}title标题不显示为false*@param{}area大小[“400px”,”500px”]或者”400px”—&…

    2022年5月16日
    113
  • Traits技法[终于解决]

    扮演“特性萃取机”角色,萃取各个迭代器的特性(迭代器的相应类型)模板特例化:提供一份template定义式,而其本身仍为templatization通过classtemplatepartial

    2021年12月18日
    44
  • js中数组截取方法

    js中数组截取方法slice()vararray=[1,5,3,9,8];varcut=array.slice(1,4);console.log(cut);打印出的结果是[5,3,9]值得注意的是,slice()不会操作原有数组,所以打印array的话,是不会变的vararray=[1,5,3,9,8];varcut=array.slice(1,4);console.log(cut);console.log(array);打印结果是[5,3,9][1,5,

    2022年5月27日
    71

发表回复

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

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