这是运行的servlet
package com.kuang.servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1、要获取下载文件的路径
String realPath = "D:\\IdeaProjects\\javaweb-01-maven02\\response\\target\\classes\\1.png";
System.out.println("下载文件的路径" + realPath);
//下载的文件名是什么,截取最后两个\\后面一位的字符串,就是文件名。
String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);
//设法想办法让浏览器能够支持(content-disposition)下载我们需要的东西,中文文件名URLEncoder.encode编码,否则有可能乱码。
resp.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
//获取下载文件的输入流
FileInputStream in = new FileInputStream(realPath);
//创建缓冲区、
int len = 0;
byte[] buffer = new byte[1024];
//获取OutputStream对象
ServletOutputStream out = resp.getOutputStream();
//将FileOutputStream流写入到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 {
doGet(req, resp);
}
}
这是web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<servlet>
<servlet-name>down</servlet-name>
<servlet-class>com.kuang.servlet.FileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>down</servlet-name>
<url-pattern>/down</url-pattern>
</servlet-mapping>
</web-app>
下面是运行结果图