一、代码
final String userAgent = request.getHeader("User-agent");
final String referer = request.getHeader("referer");
UserAgent agent = UserAgentUtil.parse(userAgent);
if (StrUtil.contains(referer, "swagger-ui")
|| agent == null
|| "MSIE".equals(agent.getBrowser().getName())
|| "MSIE11".equals(agent.getBrowser().getName())
|| "Firefox".equals(agent.getBrowser().getName())
|| userAgent.toLowerCase().startsWith("postman")
|| userAgent.toLowerCase().endsWith("hutool")
|| userAgent.toLowerCase().startsWith("apache-httpclient")) {
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
byte[] bytes = fileName.getBytes(StandardCharsets.UTF_8);
fileName = new String(bytes, StandardCharsets.ISO_8859_1);
}
response.setCharacterEncoding("UTF-8");
response.setContentType(contentType);
response.setHeader("Content-disposition",
String.format("attachment;filename=\"%s\"; filename*=utf-8'zh_cn'%s", fileName, fileName)
);