下载和导出文件名称乱码问题
只对文件名称进行乱码处理,和文件中的内容无关。
import lombok.SneakyThrows;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;/*** 下载相关工具类* @author yzx*/
public class FileCodeUtil {public static void writeHeader(String fileName){HttpServletRequest req = getRequest();HttpServletResponse rep = getResponse();rep.setContentType("application/octet-stream");String agent = req.getHeader("USER-AGENT").toLowerCase();try{rep.setHeader("Content-Disposition" , "attachment;" + encodeFileName(agent , fileName));}catch(Exception e){e.printStackTrace();}rep.setCharacterEncoding("UTF-8");}public static String encodeFileName(String fileName)throws UnsupportedEncodingException {String agent = getRequest().getHeader("USER-AGENT").toLowerCase();return encodeFileName(agent, fileName);}@SneakyThrowsprivate static String encodeFileName(String userAgent, String fileName) {String newFileName = URLEncoder.encode(fileName, "UTF-8");String rtn = (new StringBuilder()).append("filename=").append(newFileName).append("").toString();if (userAgent != null) {userAgent = userAgent.toLowerCase();if(userAgent.indexOf("msie") != -1)rtn = (new StringBuilder()).append("filename=").append(newFileName).append("").toString();else if(userAgent.indexOf("opera") != -1)rtn = (new StringBuilder()).append("filename*=UTF-8''").append(newFileName).toString();else if(userAgent.indexOf("safari") != -1)rtn = (new StringBuilder()).append("filename=").append(new String(newFileName.getBytes("UTF-8"), "ISO8859-1")).append("").toString();else if(userAgent.indexOf("applewebkit") != -1)rtn = (new StringBuilder()).append("filename=").append(newFileName).append("").toString();else if(userAgent.indexOf("mozilla") != -1)rtn = (new StringBuilder()).append("filename*=UTF-8''").append(newFileName).toString();}return rtn;}/*** 获取当前请求的HttpServletRequest对象** @return HttpServletRequest* @throws IllegalStateException 如果当前没有请求上下文*/public static HttpServletRequest getRequest() {RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();if (requestAttributes == null) {throw new IllegalStateException("No current request context available");}return ((ServletRequestAttributes) requestAttributes).getRequest();}/*** 获取当前请求的HttpServletResponse对象** @return HttpServletResponse* @throws IllegalStateException 如果当前没有请求上下文*/public static HttpServletResponse getResponse() {RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();if (requestAttributes == null) {throw new IllegalStateException("No current request context available");}return ((ServletRequestAttributes) requestAttributes).getResponse();}}
经常用,总结一点点。。。。。。。。。。。