Web development file download function (code is as follows), if the file name contains Chinese characters, it will often appear garbled and needs to be encoded.
String fileName = "测试文件.doc"; try { HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse(); response.setHeader("Content-disposition", "attachment; filename=" + fileName); response.setContentLength((int) file.length()); response.setContentType("application/octet-stream;charset=UTF-8"); byte[] b = new byte[1024]; int i = 0; FileInputStream fis = new FileInputStream(file); ServletOutputStream out = response.getOutputStream(); while ((i = fis.read(b)) > 0) { out.write(b, 0, i); } out.flush(); out.close; fis.close(); } catch (IOException e) { e.printStackTrace(); } FacesContext.getCurrentInstance().responseComplete(); return null;
Option 1: Encode the file name to Unicode
fileName = URLEncoder.encode(fileName, "UTF-8");
The file name will be converted to Unicode encoding. The test is normal under the IE browser, but under the Firefox browser The file name obtained by the test is Unicode without decoding.
Option 2: Encode the file name to ISO-8859-1
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
This method can obtain files with Chinese file names under both IE and Firefox. But if there are spaces in the file name, Firefox will truncate the file name from the spaces, and you need to replace the spaces in the file name with visible characters such as underscores before encoding.
fileName = new String(fileName.replace(" ", "_").getBytes("UTF-8"), "ISO-8859-1");
Option 3: Browser incompatibility
In Java web development, the problem of garbled file names in file download functions is often encountered. Different browsers have different solutions to this problem.
For IE, filename is UTF8-encoded through URLEncoder, while other browsers (firefox, chrome, safari, opera) need to convert bytes into ISO8859-1.
if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) { filename = URLEncoder.encode(filename, "UTF-8"); } else { filename = new String(filename.getBytes("UTF-8"), "ISO8859-1"); }
Recommended tutorial: Getting started with java development
The above is the detailed content of The file name is garbled when java downloads the file. For more information, please follow other related articles on the PHP Chinese website!