下载文件中文变成了下划线
作者:互联网
今天有个项目下载文件时发现文件名里的中文都变成了下划线(Firefox里是空格)
解决办法:针对不同浏览器对文件名进行不同格式的编码
/** * 下载文件 * @param url * @param fileName * @param contentType * @param request * @param response * @throws IOException */ private void getFile(String url, String fileName, String contentType, HttpServletRequest request, HttpServletResponse response) throws IOException { ServletOutputStream out = null; // Servlet输出流 FileInputStream ips = null; // 文件输入流 try { File file = new File(url); if (file.exists()) { // 文件名编码 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"); } // 设置响应头,控制浏览器下载该文件 response.setContentType(contentType); // 描述消息内容类型 response.setHeader("Content-Disposition", "attachment;fileName=" + fileName); response.setContentLengthLong(file.length()); ips = new FileInputStream(file); out = response.getOutputStream(); int len = 0; byte[] buffer = new byte[1024 * 10]; while ((len = ips.read(buffer)) != -1) { out.write(buffer, 0, len); } out.flush(); } } catch (Exception e) { e.printStackTrace(); } finally { out.close(); ips.close(); } }
标签:中文,下划线,param,fileName,ips,new,response,下载,out 来源: https://www.cnblogs.com/sanrenblog/p/16220895.html