博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java 文件下载
阅读量:4700 次
发布时间:2019-06-09

本文共 1808 字,大约阅读时间需要 6 分钟。

1     public void doGet(HttpServletRequest request, HttpServletResponse response) 2             throws ServletException, IOException { 3         doPost(request, response); 4     } 5  6     @SuppressWarnings("deprecation") 7     public void doPost(HttpServletRequest request, HttpServletResponse response) 8             throws ServletException, IOException { 9 10 11         String materia_url=request.getParameter("materia_url");12         String str=request.getRealPath("/")+materia_url;13     14         try {15             downLoad(str, response, false);16         } catch (Exception e) {17             18             e.printStackTrace();19         }20         21     }
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://www.cnblogs.com/molao-doing/articles/3668605.html

你可能感兴趣的文章
altium annotate 选项设置 complete existing packages
查看>>
【模式识别与机器学习】——SVM举例
查看>>
【转】IT名企面试:微软笔试题(1)
查看>>
IO流入门-第十章-DataInputStream_DataOutputStream
查看>>
DRF的分页
查看>>
Mysql 模糊匹配(字符串str中是否包含子字符串substr)
查看>>
python:open/文件操作
查看>>
流程控制 Day06
查看>>
Linux下安装Tomcat
查看>>
windows live writer 2012 0x80070643
查看>>
tomcat 和MySQL的安装
查看>>
git常用操作
查看>>
京东SSO单点登陆实现分析
查看>>
u-boot启动第一阶段
查看>>
MySQL批量SQL插入性能优化
查看>>
定义列属性:null,default,PK,auto_increment
查看>>
用户画像展示
查看>>
C#中StreamReader读取中文出现乱码
查看>>
使用BufferedReader的时候出现的问题
查看>>
批处理文件中的路径问题
查看>>