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

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

1 @Controller   2 public class FileController implements ServletContextAware{    3     //Spring这里是通过实现ServletContextAware接口来注入ServletContext对象    4     private ServletContext servletContext;    5    6    7     @RequestMapping("file/download")    8     public void fileDownload(HttpServletResponse response){    9         //获取网站部署路径(通过ServletContext对象),用于确定下载文件位置,从而实现下载   10         String path = servletContext.getRealPath("/");   11       response.rset();         //清楚空格等操作12         //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型   13         response.setContentType("multipart/form-data");   14         //2.设置文件头:最后一个参数是设置下载文件名(假如我们叫a.pdf)   15         response.setHeader("Content-Disposition", "attachment;fileName="+"a.pdf");   16         ServletOutputStream out;   17         //通过文件路径获得File对象(假如此路径中有一个download.pdf文件)   18         File file = new File(path + "download/" + "download.pdf");   19   20         try {   21             FileInputStream inputStream = new FileInputStream(file);   22   23             //3.通过response获取ServletOutputStream对象(out)   24             out = response.getOutputStream();   25   26             int b = 0;   27             byte[] buffer = new byte[512];   28             while (b != -1){   29                 b = inputStream.read(buffer);   30                 //4.写到输出流(out)中   31                 out.write(buffer,0,b);   32             }   33             inputStream.close();   34             out.close();   35             out.flush();   36   37         } catch (IOException e) {   38             e.printStackTrace();   39         }   40     }   41   42     @Override  43     public void setServletContext(ServletContext servletContext) {   44         this.servletContext = servletContext;   45     }   46 }

 

转载于:https://www.cnblogs.com/jiang--nan/p/7864981.html

你可能感兴趣的文章
HTC Sensation G14开盒
查看>>
lock_sga引起的ksvcreate :process(m000) creation failed
查看>>
数据库插入数据乱码问题
查看>>
OVER(PARTITION BY)函数用法
查看>>
altium annotate 选项设置 complete existing packages
查看>>
【模式识别与机器学习】——SVM举例
查看>>
【转】IT名企面试:微软笔试题(1)
查看>>
IO流入门-第十章-DataInputStream_DataOutputStream
查看>>
DRF的分页
查看>>
Mysql 模糊匹配(字符串str中是否包含子字符串substr)
查看>>
IIS的ISAPI接口简介
查看>>
python:open/文件操作
查看>>
16 乘法口诀输出
查看>>
mac 常用地址
查看>>
鼠标经过切换图片
查看>>
流程控制 Day06
查看>>
Linux下安装Tomcat
查看>>
windows live writer 2012 0x80070643
查看>>
C程序的启动和终止
查看>>
tomcat 和MySQL的安装
查看>>