超链接指向的资源如果能被浏览器解析,则点击后显示;不能的话则展示下载提示框 ``` <!DOCTYPE html>
- 针对以上问题,我们想让浏览器弹窗提示下载,无论什么类型
- download.html
<!DOCTYPE html>
<!-- 超链接指向的资源如果能被浏览器解析,则点击后显示;不能的话则展示下载提示框-->
<a href="/WebDemo_war_exploded/downloadServlet?filename=图标.png">图片</a>
- DownloadServlet
> response.setHeader("content-disposition","attachment;filename="+filename);
package com.code.web;
import com.code.web.util.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 {
ServletContext servletContext = this.getServletContext();
// 文件地址
String filename = request.getParameter("filename");
String realPath = servletContext.getRealPath("/imgs/" + filename);
// 设置响应体文件类型
String mimeType = servletContext.getMimeType(realPath);
response.setHeader("content-type",mimeType);
// 防止中文乱码
String header = request.getHeader("user-agent");
filename = DownloadUtils.getileName(header, filename);
// 打开响应体方式
response.setHeader("content-disposition","attachment;filename="+filename);
// 响应体图片字节数据
FileInputStream fileInputStream = new FileInputStream(realPath);
ServletOutputStream outputStream = response.getOutputStream();
byte[] buff = new byte[1024*8];
int len = 0;
while ((len = fileInputStream.read(buff)) != -1){
outputStream.write(buff,0,len);
}
fileInputStream.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
<a name="xSeNm"></a>
#### 防止中文名乱码工具类
package com.code.web.util;
import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Base64;
public class DownloadUtils {
public static String getileName(String agent,String filename) throws UnsupportedEncodingException {
if (agent.contains("MSIE")) {
// IE浏览器
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+", " ");
} else if (agent.contains("Firefox")) {
// 火狐浏览器
Base64.Encoder encoder = Base64.getEncoder();
String str = encoder.encodeToString(filename.getBytes("utf-8"));
filename = "=?utf-8?B?" + str + "?=";
} else {
// 其它浏览器
filename = URLEncoder.encode(filename, "utf-8");
}
return filename;
}
} ```