这篇文章跟大家分析一下“springmvc中下载中文文件名称为下划线的解决方法”。内容详细易懂,对“springmvc中下载中文文件名称为下划线的解决方法”感兴趣的朋友可以跟着小编的思路慢慢深入来阅读一下,希望阅读后能够对大家有所帮助。下面跟着小编一起深入学习“springmvc中下载中文文件名称为下划线的解决方法”的知识吧。
springboot项目中,在下载文件的时候,通过封装ResponseEntity,将文件流写入body,这种下载文件的方式,造成了下载的文件名为正文显示为下划线的形式;
直接将输入的文件名的编码格式定义成GBK格式;
如下代码
public static ResponseEntity<FileSystemResource> export(File file) throws UnsupportedEncodingException { if (file == null) { return null; } //这个位置对文件名进行编码 String fileName = new String (file.getName().getBytes("GBK"),"ISO-8859-1"); HttpHeaders headers = new HttpHeaders(); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Content-Disposition", "attachment; filename=" +fileName); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); headers.add("Last-Modified", new Date().toString()); headers.add("ETag", String.valueOf(System.currentTimeMillis())); return ResponseEntity .ok() .headers(headers) .contentLength(file.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(new FileSystemResource(file)); }
public static void exportToExcel(String uid, String name, String htmlText, HttpServletRequest request, HttpServletResponse response) { htmlText = htmlText.replaceFirst("<table>", "<tableFirst>"); htmlText = htmlText.replaceAll("<table>", "<table cellpadding=\"3\" cellspacing=\"0\" border=\"1\" rull=\"all\" style=\"border-collapse: collapse\">"); htmlText = htmlText.replaceFirst("<tableFirst>", "<table>"); try (OutputStream out = response.getOutputStream()) { String fileName = name+ "_" + DateUtils.getNow("yyyyMMddHHmmss"); // fileName = new String(fileName.getBytes(),"utf-8")+ ".xls"; if ("large".equals(htmlText)) { ReportingPo report = reportingService.getByUid(uid); Map<String, Object> formParameters = generationService.getFormParameters(request.getParameterMap(), report.getDataRange()); ReportTable reportTable = generationService.getReportTable(report, formParameters); htmlText = reportTable.getHtmlText(); } // response.reset(); response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"),"iso-8859-1")+ ".xls"); // response.setHeader("Content-Disposition", String.format("attachment; filename=%s", fileName)); response.setContentType("application/vnd.ms-excel; charset=utf-8"); response.setCharacterEncoding("utf-8"); response.addCookie(new Cookie("fileDownload", "true")); // out.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }); // 生成带bom的utf8文件 out.write(htmlText.getBytes("utf-8")); out.flush(); } catch (Exception ex) { throw new RuntimeException(ex); } }
new String(fileName.getBytes("utf-8"),"iso-8859-1")+ ".xls"
关于springmvc中下载中文文件名称为下划线的解决方法就分享到这里啦,希望上述内容能够让大家有所提升。如果想要学习更多知识,请大家多多留意小编的更新。谢谢大家关注一下亿速云网站!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。