如何用用Response下载文件(图片)
大致步骤:
- 获取下载文件路径
- 确定下载文件路径
- 设置浏览器支持的编码格式
- 获取下载文件的输入流
- 创建缓冲区
- 获取OutputStream对象
- 将FileInputStream流写入到buffer缓冲区中,使用OutputStream流将缓冲区的数据输出到客户端
- 配置web.xml
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取下载文件路径
String realPath = "D:\\学习类\\Projects-java\\java-1-test\\JavaWebDemo\\src\\main\\resources\\111.png";
System.out.println("下载文件路径:" + realPath);
//确定下载文件路径
String fileName = realPath.substring(realPath.lastIndexOf("//") + 1);
//设置浏览器支持的编码格式
resp.setHeader("Content-Disposition", "attachment;filename = " + URLEncoder.encode(fileName,"UTF-8"));
//获取下载文件的输入流
FileInputStream in = new FileInputStream(fileName);
//创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
//获取OutputStream对象
ServletOutputStream out = resp.getOutputStream();
//将FileInputStream流写入到buffer缓冲区中,使用OutputStream流将缓冲区的数据输出到客户端
while ((len = in.read(buffer)) > 0){
out.write(buffer,0,len);
}
in.close();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>filedown</servlet-name>
<servlet-class>com.xiaomu.FileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>filedown</servlet-name>
<url-pattern>/down</url-pattern>
</servlet-mapping>
</web-app>
注意下载servlet-api和servlet-jsp
//web.xml的头
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
</web-app>
//javax.servlet-api
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
//jsp
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
本文来自博客园,作者:萧木XIAOMU,转载请注明原文链接:https://www.cnblogs.com/xiaomu25/articles/16852679.html