SpringBoot项目打包成jar后,下载Excel文件打开失败

前言

笔者在SpringBoot项目中,有个下载Excel模板的需求,项目在idea中跑起来后,文件下载成功并且打开正常。当项目打包成jar后部署到测试环境,下载下来的模板无法打开,针对这个问题,特此记录。

解决方案:

废话不多说,直接上代码,这种方式亲测有效。
注: 模板放在resources/static/pattner目录下
下载接口:

    /**
     * 下载导入模板文件
     * @param response
     */
    @ApiOperation("下载商户资质审核导入模板文件")
    @GetMapping("/download/pattern")
    public void downloadPattern(HttpServletRequest request, HttpServletResponse response){
        //文件名
        String fileName = "商户资质审核导入模板";
        //获取类路径下的资源,获取输入流
        try(InputStream in = new ClassPathResource("\\static\\pattern\\商户资质审核导入模板.xlsx").getInputStream()) {
            XSSFWorkbook workbook = new XSSFWorkbook(in);
            FileUtil.downFile(fileName,response,workbook);
        }catch (Exception e){
            e.printStackTrace();
            throw new Exception("下载失败",0);
        }
    }

download()方法:

/**
 * 文件工具
 */
@Log4j2
public class FileUtil {
	 /**
     * 下载Excel文件
     * @param fileName  下载文件名
     * @param response
     * @param workbook Excel工作簿对象
     * @throws IOException
     */
    public static void downFile(String fileName,
                                HttpServletResponse response, XSSFWorkbook workbook) {
        try(OutputStream os = response.getOutputStream()) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.reset();
            response.setContentType("application/binary;charset=utf-8");
            response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");
            workbook.write(os);
            os.flush();
        } catch (Exception e) {
            log.info("fileName: "+fileName + ", 下载失败! ",e);
            throw new Exception();
        }
    }
}

-----------------------------------学习不易,需要坚持-----------------------

你可能感兴趣的:(SpringBoot)