Problem Description:
JavaWeb project, which realizes downloading server-side files in the browser. When the file name contains Chinese, the file name downloaded by the browser is garbled or not displayed (only the suffix)
Process analysis:
Browser -- > server -- > browser
1. click the file to be downloaded on the browser (including Chinese characters)
2. the server obtains the parameters from the browser, finds the target file on the server, and writes it to the browser through the IO stream
3. the browser creates the corresponding file according to the Header information returned by the server. At this time, the file name appears Chinese garbled
Solution:
1. modify the configuration file of Tomcat
Accessing files on the server through hyperlinks (href attribute of a tag) is a GET request. It is recommended to check conf/server XML, whether to add URIEncoding="UTF-8" to the two connectors, as shown in the following figure. After this setting, the Chinese parameters passed by the browser to the server should not be garbled.
<Connector port="8888" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8" /> <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8"/>
If you do not have permission to modify the configuration file of Tomcat for some reasons, you can transcode the file name in your code
filename = new String(filename.getBytes("ISO-8859-1"),"UTF-8"); // Need to catch exception
2.User-Agent
Set different encoding formats for file names according to different browsers
1) IE, EDGE and other Microsoft browsers: the file name is encoded in UTF-8 format
2) Other browsers: file names are encoded in ISO-8859-1 format
Determine the type of browser:
public class HttpUtils { private static String[] IEBrowserSignals = {"MSIE", "Trident", "Edge"}; public static boolean isMSBrowser(HttpServletRequest request) { String userAgent = request.getHeader("User-Agent"); for (String signal : IEBrowserSignals) { if (userAgent.contains(signal)) return true; // Is a Microsoft browser } return false; // Other browsers } } }
Downloadutil Java excerpt code
response.setContentType("application/octet-stream"); // Binary stream boolean isMSIE = HttpUtils.isMSBrowser(request); // Determine whether it is a Microsoft browser if (isMSIE) { // The solution of garbled code in Internet Explorer fileName = URLEncoder.encode(fileName, "UTF-8"); } else { // Universal garbled code problem solving fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1"); } // Double quotation marks around the file name can solve the problem that the file name is truncated when the firefox browser encounters spaces response.setHeader("Content-disposition", "attachment;filename=\"" + fileName + "\"");
Reference website: