文件下载中文文件名乱码和FireFox名中空格被截断问题。
解决方法一:
//只能字符被截断问题,但是中文会出现乱码,可能需要对其字符进行编码(这没有测试)response.addHeader("Content-Disposition", "attachment; filename=\"" + fileShowName+\"");
解决方法二:在Edge、Opera、IE、FireFox、Google等主流浏览器下都测试过。
private void downloadFile(InputStream in ,HttpServletRequest request, HttpServletResponse response ) throws IOException { String fileShowName ; String agent = request.getHeader("USER-AGENT"); System.out.println(" 浏览器agent信息 ---》" +agent); //IE内核浏览器,或者Edge浏览器 if( null != agent && (-1 != agent.indexOf("MSIE") || -1 != agent.indexOf("Edge"))){ fileShowName = URLEncoder.encode(this.fileShowName, "utf-8"); //处理IE文件名空格变成"+"的问题 fileShowName = fileShowName.replace("+", "%20"); }else{ //非IE fileShowName = URLDecoder.decode(this.fileShowName, "utf-8"); //解决火狐,文件名中空格被截断的情况 fileShowName = "=?UTF-8?B?" + (new String (Base64.encodeBase64(this.fileShowName.getBytes("UTF-8")))) + "?="; } response.addHeader("Content-Disposition", "attachment; filename=" + fileShowName); response.setContentType("application/octet-stream"); response.setHeader("Content-Length", fileSize + ""); OutputStream out = response.getOutputStream(); byte[] buffer = new byte[ bufferSize ]; int len; while ((len = in.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, len); } out.flush(); out.close(); in.close(); }