package com.ghgj.downLoad;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
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 org.apache.catalina.LifecycleListener;
@WebServlet("/DownLoad")
public class DownLoad extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//获取文件名
String filename = request.getParameter("filename");
//获取文件对应的真实的路径
ServletContext context = request.getServletContext();
String path = context.getRealPath("/resources/"+filename);
//通过路径创建流,把文件放入对应的输入流里面
InputStream is=new FileInputStream(path);
//保证下载的名字是自己所需要的
String agent=request.getHeader("User-Agent");
String fileName= DownLoadUtils.getFileName(agent, filename);
//获取文件类型,需要用到servletContent里面的getMimeType方法
String mimeType = context.getMimeType(filename);
//告诉浏览器文件类型
response.setHeader("content-type", mimeType);
//告诉浏览器不要打开,直接下载,同时告诉浏览器下载之后的文件名什么
response.setHeader("content-disposition","attachment;filename="+fileName);
//响应输出流
ServletOutputStream os = response.getOutputStream();
int line=0;
byte[] b=new byte[1024*10];
while((line=is.read(b))!=-1){
os.write(b,0,line);
}
os.close();
is.close();
}
}