@WebServlet("/downFile.do")
public class DownFileServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html,charset=utf-8");
//获取真实路径
String realPath = getServletContext().getRealPath("/");
//获取参数
String fileName = req.getParameter("fileName");
//文件
File srcFile = new File(realPath+fileName);
if(srcFile.exists()&&srcFile.isFile()){
//设置响应头信息
//设置响应类型(浏览器无法使用某种方式或激活某个程序来处理的类型)
resp.setContentType("application/x-msdownload");
//设置头信息
resp.setHeader("Content-Disposition","attachment;filename="+fileName);
InputStream is = new FileInputStream(srcFile);
ServletOutputStream os = resp.getOutputStream();
int len=0;
byte[] car = new byte[1024];
while((len=is.read())!=-1){
os.write(car,0,len);
}
os.flush();
os.close();
is.close();
}else {
System.out.println("文件不存在");
}
}
}
响应响应头设置
最新推荐文章于 2024-05-25 08:00:00 发布