springboot 下载文件_idea中jar包已经导入但是还是报错

(1) 2024-06-24 11:23

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说
springboot 下载文件_idea中jar包已经导入但是还是报错,希望能够帮助你!!!。

SpringBoot下载resource下的文件(POI)

1、导入依赖

<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-poi</artifactId> <version>${ 
   hutool.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>${ 
   poi.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>${ 
   poi.version}</version> </dependency> 

2、编写controller

@ApiOperation(value = "下载默认模板文件", notes = "下载默认模板文件") @GetMapping(value = "/excel-template/{sort}") public void downloadHeadTemplate(@PathVariable("sort") String sort) throws Exception { 
    HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse(); response.setCharacterEncoding("UTF-8"); String fileName = sort+"模板.xlsx"; String template; template = "/excel/reset_default_setting.xlsx"; response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename=" + encodeFileName(fileName)); try (InputStream inStream = MedalController.class.getResourceAsStream(template); OutputStream outputStream = response.getOutputStream()) { 
    byte[] b = new byte[1000]; int len; while ((len = inStream.read(b)) > 0) { 
    outputStream.write(b, 0, len); } } catch (IOException e) { 
    log.warn("MedalController getExcelTemplate put content failed,cause:{}", e); } } 

3、校验浏览器,改变文件名

private String encodeFileName(String fileName) { 
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String codeFileName = null; String agent = request.getHeader("User-Agent"); try { 
    if (agent.contains("MSIE") || agent.contains("Trident")) { 
    codeFileName = java.net.URLEncoder.encode(fileName, "UTF-8"); } else { 
    // 非IE浏览器的处理: codeFileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); } } catch (Exception e) { 
    e.printStackTrace(); } return codeFileName; } 

今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

上一篇

已是最后文章

下一篇

已是最新文章

发表回复