Servlet 文件下载提示保存文件 Content-Disposition :attachment和inline的区别
前端页面:
<body>
<!-- 无设置默认打开 inline -->
<a href="img/美女.jpg"><img src="img/美女.jpg" >图片1</a><br/>
<a href="mp4/01.课程内容简介.mp4">视频</a>
<hr/>
<!-- attachment -->
<a href="DownloadServlet2?filename=美女.jpg">图片1 点击下载</a><br/>
<a href="DownloadServlet2?filename=01.课程内容简介.mp4">视频 点击下载</a>
@WebServlet("/DownloadServlet2")
public class DownloadServlet2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String filename = request.getParameter("filename");
String suffix = filename.substring(filename.lastIndexOf(".")+1);
String path = null;
if(suffix.equals("jpg")){
path = getServletContext().getRealPath("img");
}else if (suffix.equals("mp4")){
path = getServletContext().getRealPath("mp4");
}
if(path != null){
FileInputStream fis = new FileInputStream(path + "/" + filename);
response.setHeader("content-disposition","attachment; filename="+DownloadUtils.encodeFilename(request,filename));
ServletOutputStream sos = response.getOutputStream();
byte[] lens = new byte[8192];
int len;
while((len = fis.read(lens))!= -1){
sos.write(lens,0,len);
}
sos.close();
fis.close();
}
}
public class DownloadUtils {
/**
* 解决下载时,中文文件名称乱码问题<br>
*
* @param request request对象
* @param filename 你想让用户保存的文件名称
*/
public static String encodeFilename(HttpServletRequest request, String filename){
try{
String agent = request.getHeader("User-Agent");
if (agent.contains("MSIE")) {
// IE浏览器
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+", " ");
} else if (agent.contains("Firefox")) {
// 火狐浏览器
//BASE64Encoder base64Encoder = new BASE64Encoder();
Base64.Encoder base64Encoder = Base64.getEncoder();
filename = base64Encoder.encodeToString(filename.getBytes("utf-8"));
filename = "=?utf-8?B?"+ filename + "?=";
} else {
// 其它浏览器
filename = URLEncoder.encode(filename, "utf-8");
}
}catch(Exception e){
e.printStackTrace();
}
return filename;
}
}
来源:CSDN
作者:缘醉丶莫求
链接:https://blog.csdn.net/qq_37698425/article/details/104094882