参考链接:关于URL编码
1、概述
一般要对文件名称编码(主要是中文名称和特殊符号编码的问题),不然下载的时候会出异常,异常在后面
package com.mocha.order.util;import com.mocha.order.constant.BrowserConstant;
import com.mocha.order.constant.BrowserKernelConstant;
import com.mocha.order.constant.RequestHeadConstant;
import com.mocha.order.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;/*** http响应头工具类* 用于设置不通的头部参数** @author yyy*/
@Slf4j
public class ResponseHeadUtils {/*** 空格*/private static final String SPACE = "+";/*** 空格转码*/private static final String ENCODED_SPACE = "%20";/*** 浏览器列表*/private static final List<String> BROWSERS_TO_CHECK = Arrays.asList(BrowserConstant.MSIE, BrowserConstant.EDGE, BrowserConstant.EDG, BrowserKernelConstant.TRIDENT);/*** 设置响应头的ContentDisposition** @param fileName 文件名称* @param httpServletResponse http响应头*/public static void setContentDisposition(final String fileName, final HttpServletResponse httpServletResponse) {try {final String fileNameEncode = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());final String encodedFileName = fileNameEncode.replace(SPACE, ENCODED_SPACE);httpServletResponse.setHeader(RequestHeadConstant.CONTENT_DISPOSITION,"attachment; filename=" + encodedFileName + ";filename*=UTF-8''" + encodedFileName);} catch (final UnsupportedEncodingException e) {log.error("设置响应头异常:不支持的编码异常!", e);throw new CustomException("不支持的编码异常!");}}/*** 判断是否是微软浏览器** @param userAgent 浏览器信息* @return true:是微软浏览器;false:不是微软浏览器*/private static boolean isMicrosoftBrowser(final String userAgent) {return BROWSERS_TO_CHECK.stream().anyMatch(browser -> StringUtils.containsIgnoreCase(userAgent, browser));}/*** 设置响应头的ContentType** @param contentType 内容类型枚举* @param httpServletResponse http响应头*/public static void setContentType(final String contentType, final HttpServletResponse httpServletResponse) {httpServletResponse.setContentType(contentType);}
}
前端对文件名称解码:
必须使用decodeURIComponent解码,不使用decodeURI,不然对于特殊符号(; / ? : @ & = + $ , #),decodeURI无法解码
const contentDisposition = xhr.getResponseHeader('Content-Disposition');
const fileName = extractFileNameFromContentDisposition(contentDisposition); // 默认文件名,如果无法从响应中获取
const decodeFilename = decodeURIComponent(fileName); // 使用从后端获取的文件名
前端解码:
1、decodeURIComponent()
功能: 用于解码整个 URI 组件,能够解码任意的百分号编码(%xx)。
用法: 适用于解码附加在 URI 组件中的信息,如查询字符串中的参数。
示例
const encodedComponent = "Hello%20World%21"; // "Hello World!"
const decodedComponent = decodeURIComponent(encodedComponent);
console.log(decodedComponent); // 输出: Hello World!
2、decodeURI()
功能: 用于解码完整的 URI,但不会解码某些保留字符(如 #, ?, &),因为这些字符在 URI 中有特殊含义。
用法: 适用于解码整个 URI,而不干扰其结构。
const encodedURI = "http%3A%2F%2Fexample.com%2FHello%20World%21"; // "http://example.com/Hello World!"
const decodedURI = decodeURI(encodedURI);
console.log(decodedURI); // 输出: http://example.com/Hello World!
2、常见浏览器的UserAgent
- Chorme
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36
- Edge
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0
- Firefox
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:127.0) Gecko/20100101 Firefox/127.0
- 360极速
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.160 Safari/537.36
3、异常
23-Aug-2024 16:48:56.580 警告 [http-nio-8480-exec-1] org.apache.coyote.http11.Http11Processor.prepareResponse HTTP响应头信息[Content-Disposition] 值[attachment; filename=测.png;filename*=UTF-8''%E6%B5%8B.png],由于无效已从响应中移除java.lang.IllegalArgumentException: 代码点[27,979]处的Unicode字符[测]无法编码,因为它超出了允许的0到255范围。at org.apache.tomcat.util.buf.MessageBytes.toBytesSimple(MessageBytes.java:310)at org.apache.tomcat.util.buf.MessageBytes.toBytes(MessageBytes.java:283)at org.apache.coyote.http11.Http11OutputBuffer.write(Http11OutputBuffer.java:385)at org.apache.coyote.http11.Http11OutputBuffer.sendHeader(Http11OutputBuffer.java:364)at org.apache.coyote.http11.Http11Processor.prepareResponse(Http11Processor.java:1046)at org.apache.coyote.AbstractProcessor.action(AbstractProcessor.java:376)at org.apache.coyote.Response.action(Response.java:207)at org.apache.coyote.http11.Http11OutputBuffer.doWrite(Http11OutputBuffer.java:187)at org.apache.coyote.Response.doWrite(Response.java:613)at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:333)at org.apache.catalina.connector.OutputBuffer.flushByteBuffer(OutputBuffer.java:780)at org.apache.catalina.connector.OutputBuffer.append(OutputBuffer.java:677)at org.apache.catalina.connector.OutputBuffer.writeBytes(OutputBuffer.java:380)at org.apache.catalina.connector.OutputBuffer.write(OutputBuffer.java:358)at org.apache.catalina.connector.CoyoteOutputStream.write(CoyoteOutputStream.java:103)at com.opensymphony.module.sitemesh.filter.RoutableServletOutputStream.write(RoutableServletOutputStream.java:118)at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1793)at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1769)at org.apache.commons.io.IOUtils.copy(IOUtils.java:1744)at com.mocha.order.controller.GoodNumberAuditManagerController.downloadAuditFileByAuditFileId(GoodNumberAuditManagerController.java:111)at com.mocha.order.controller.GoodNumberAuditManagerController$$FastClassBySpringCGLIB$$13f3585.invoke(<generated>)at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)at com.mocha.order.controller.GoodNumberAuditManagerController$$EnhancerBySpringCGLIB$$3c3a1490.downloadAuditFileByAuditFileId(<generated>)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:498)at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)at javax.servlet.http.HttpServlet.service(HttpServlet.java:529)at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)at javax.servlet.http.HttpServlet.service(HttpServlet.java:623)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:199)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:144)at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:168)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:144)at com.mocha.order.filter.XssAttackInterceptor.doFilter(XssAttackInterceptor.java:24)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:168)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:144)at com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent(SiteMeshFilter.java:129)at com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:77)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:168)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:144)at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:168)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:144)at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:61)at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108)at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137)at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108)at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137)at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:450)at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:387)at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:347)at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:263)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:168)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:144)at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:168)at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90)at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:481)at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:130)at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:660)at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:346)at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:388)at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:928)at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1791)at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1190)at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:63)at java.lang.Thread.run(Thread.java:748)