@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置请求编码
request.setCharacterEncoding("utf-8");
//获取需要下载的文件名
String fileName = request.getParameter("fileName") ;
System.out.println(fileName);
//设置两个 响应头
response.addHeader("content-Type", "application/octet-stream");
//获取客户端的User-Agent (判断用户用的什么浏览器)
String browser = request.getHeader("User-Agent");
if (-1 < browser.indexOf("MSIE 6.0") || -1 < browser.indexOf("MSIE 7.0")) {
// IE6, IE7 浏览器
response.addHeader("content-disposition",
"attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1"));
} else if (-1 < browser.indexOf("MSIE 8.0")) {
// IE8
response.addHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
} else if (-1 < browser.indexOf("MSIE 9.0")) {
// IE9
response.addHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
} else if (-1 < browser.indexOf("Chrome")) {
// 谷歌
response.addHeader("content-disposition",
"attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));
} else if (-1 < browser.indexOf("Safari")) {
// 苹果
response.addHeader("content-disposition",
"attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1"));
} else {
// 火狐或者其他的浏览器
response.addHeader("content-disposition",
"attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));
}
// response.addHeader("content-Disposition", "attachment;filename="+fileName);
//Servlet通过文件的地址将文件转为输入流 读到Servlet 中
String path = "res/"+fileName ;(我这里是绝对位置,可根据自己的需要进行修改)
InputStream in = getServletContext().getResourceAsStream(path) ;
//通过输出流 将刚才已转为输入流的文件输出给用户
ServletOutputStream out = response.getOutputStream();
byte[] bs = new byte[1024] ;
int len = -1 ;
while( ( len=in.read(bs) ) != -1 ) {
out.write(bs,0,len);;
}
out.close();
in.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
实现文件下载及不同浏览器的乱码问题
最新推荐文章于 2023-06-08 16:02:22 发布