package com.lsm.web.servlet;
import com.lsm.utils.DownLoadUtils;
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.FileInputStream;
import java.io.IOException;
@WebServlet("/downLoadServlet")
public class DownLoadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取要下载的文件名称
String filename = request.getParameter("filename");
//2.找到文件在服务器中的真实路径
ServletContext servletContext = this.getServletContext();
String realPath = servletContext.getRealPath("/image/" + filename);
//3.关联输入流
FileInputStream fis=new FileInputStream(realPath);
//设置响应文件类型
String mimeType = servletContext.getMimeType(filename);
response.setHeader("content-type",mimeType);
//通过user-agenet判断来源那个浏览器
String agent = request.getHeader("user-agent");
System.out.println(agent);
//借助工具类解决附件弹窗的中文乱码
filename = DownLoadUtils.getFileName(agent,filename);
//下载时弹出附件框
response.setHeader("content-disposition","attachment;filename="+filename);
//通过sos交互到浏览器
ServletOutputStream sos = response.getOutputStream();
byte[] buff=new byte[1024*10];
int len=0;
while ((len=fis.read(buff))!=-1){
sos.write(buff,0,len);
}
fis.close();
}
}
|
|