这里使用Servlet的dopost方法来实现数据回传给客户端
步骤:1.获取下载的文件名
2.获取ServletContext对象
3.获取要下载的文件类型
4.回传前,告诉客户端返回的数据类型
5.设置响应头,告诉客户端此文件用于下载
6.通过ServletContext对象获取输入流,将文件输入到内存中
7.获取响应的输出流,并同时将输入流的内容复制给该输出流响应给客户端
public class DownloadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取下载的文件名
String downloadFileName="2000057.jpg";
//2、读取要下载的文件内容(通过ServletContext对象可以读取)
ServletContext servletContext = getServletContext();
//获取要下载的文件类型
String mimeType = servletContext.getMimeType("/downloads/" + downloadFileName);
System.out.println("下载的文件类型:"+mimeType);
//4、在回传前,通过响应头告诉客户端返回的数据类型
resp.setContentType(mimeType);
//5、还要告诉客户端收到的数据是用于下载使用(还是使用响应头)
//Content-Disposition响应头:表示收到的数据怎么处理
//attachment表示附件,表示下载使用
//filename=指定下载的文件名
resp.setHeader("Content-Disposition","attachment;filename="+downloadFileName);
//获取一个输入流,准备将内容输入内存中
InputStream resource = servletContext.getResourceAsStream("/downloads/" + downloadFileName);
//获取相应的输出流
ServletOutputStream outputStream = resp.getOutputStream();
//读取输入流中的数据,复制给输出流,输出给客户端
IOUtils.copy(resource,outputStream);
}
}



