通过浏览器客户端访问Servlet,实现存储于Tomcat服务器上的资源文件的下载效果,主要结合ServletResponse与IO流文件操作实现。原理图示如下:
指定文件目录
首先新建项目servletDemo2,指定用于存放文件的路径为:
servletDemo2/files/
编写Servlet类
通过继承HttpServlet,重写doGet()和doPost()方法,实现文件下载功能,此处约定使用GET请求,请求参数为:fname。
package com.xwd.demo;
import jdk.internal.util.xml.impl.Input;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
/**
* @ClassName FileDownLoad
* @Description: com.xwd.demo
* @Auther: xiwd
* @Date: 2022/2/3 - 02 - 03 - 23:08
* @version: 1.0
*/
public class FileDownLoad extends HttpServlet {
private static final String FILE_DIR="files";
//methods
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//super.doGet(req, resp);
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//super.doPost(req, resp);
request.setCharacterEncoding("UTF-8");
//解析参数
String fname = request.getParameter("fname");
System.out.println(fname);
//获取ServletContext对象
ServletContext servletContext = request.getServletContext();
//获取相对路径
String realPath = servletContext.getRealPath(FILE_DIR+ File.separator + fname);
System.out.println(realPath);
//获取媒体类型
String mimeType = servletContext.getMimeType(fname);
//设置响应头
response.setHeader("Content-Disposition","attachment;filename="+realPath);
//设置响应体编码格式
response.setCharacterEncoding("UTF-8");
//设置媒体类型
response.setContentType(mimeType);
System.out.println(mimeType);
//以字节流输出文件
InputStream is = new FileInputStream(realPath);
ServletOutputStream os = response.getOutputStream();
byte[] buffer=new byte[1024];
int len=-1;
while ((len = is.read(buffer)) != -1) {
os.write(buffer,0,len);
}
//关闭流
os.close();
is.close();
}
}
配置web.xml文件
使用Servlet3.0以上的版本,也可直接使用@WebServlet注解配置
web.xml文件配置
<!-- FileDownLoad-->
<servlet>
<servlet-name>filedownLoad</servlet-name>
<servlet-class>com.xwd.demo.FileDownLoad</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>filedownLoad</servlet-name>
<url-pattern>/filedownLoad</url-pattern>
</servlet-mapping>
注解配置
@WebServlet(
name = "filedownload",
value = {"/filedownload"}
)
public class FileDownLoad extends HttpServlet {
}