版权声明:yanghaha的原创博客 https://blog.csdn.net/qq_44758435/article/details/90636619
文件下载
需要先导入两个jar包
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
String fileName = request.getParameter("fileName");
//下载文件,需要设置两个响应头
//application/octet-stream任意文件类型
response.addHeader("content-Type", "application/octet-stream");
//对于不同浏览器进行处理
//根据请求头user-agent
//attachment打开对话框下载 inline直接打开
String agent = request.getHeader("User-agent");
if(agent.indexOf("Firefox")!=-1) {
response.addHeader("content-Disposition", "attachment;fileName==?UTF-8?B?"+Base64.getEncoder().encodeToString(fileName.getBytes("utf-8"))+"?=");
}else if(agent.indexOf("Edge")!=-1) {
response.addHeader("content-Disposition", "attachment;fileName="+URLEncoder.encode(fileName, "utf-8"));
}
//servlet 通过文件路径将文件转换为输入流 读到servlet中
InputStream in = getServletContext().getResourceAsStream("/res/"+fileName);
//输出流
ServletOutputStream out = response.getOutputStream();
byte[] bt = new byte[10];
int len = -1;
//将缓冲区的读取bt
while((len=in.read(bt))!=-1) {
//将bt里的输出到response
out.write(bt,0,len);
}
out.close();
in.close();
文件下载名中文乱码问题
(1).edge
response.addHeader("content-Disposition", "attachment;fileName="+URLEncoder.encode(fileName, "utf-8"));
(2).火狐
response.addHeader("content-Disposition", "attachment;fileName==?UTF-8?B?"+Base64.getEncoder().encodeToString(fileName.getBytes("utf-8"))+"?=");
(3).综合处理
String agent = request.getHeader("User-agent");
if(agent.indexOf("Firefox")!=-1) {
response.addHeader("content-Disposition", "attachment;fileName==?UTF-8?B?"+new String(Base64.encodeBase64(fileName.getBytes("utf-8")))+"?=");
}else if(agent.indexOf("Edge")!=-1) {
response.addHeader("content-Disposition", "attachment;fileName="+URLEncoder.encode(fileName, "utf-8"));
}