springboot下载resource下的静态资源,下载excel文件损坏

在resource下新建文件目录【template】

启动之后查看编译结果

编写下载模板方法

public void downLoadTemplate(HttpServletResponse response) {
    FileInputStream fis = null;
    ServletOutputStream sos = null;
    try {
        String fileName = URLEncoder.encode("用户管理导入模板", "UTF-8");
        String path = "template/用户管理导入模板.xlsx";
        //设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        response.setHeader("Content-disposition",         "attachment;filename="+fileName+".xlsx");
        ClassPathResource classPathResource = new ClassPathResource(path);
        fis = new FileInputStream(classPathResource.getFile());
        sos = response.getOutputStream();
        IOUtils.copy(fis,sos);
    } catch (Exception e) {
        throw new SysException("下载文件失败:" + e.getMessage());
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (sos != null) {
                sos.flush();
                sos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

下载文件,发现文件可以正常下载,但是文件被破坏

查看原文件大小和编译后文件大小是否一致,如果不一致,则说明编译文件时出现问题。

解决方式:

①在pom中添加以下配置:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <version>2.6</version>
    <artifactId>maven-resources-plugin</artifactId>
    <configuration>
        <encoding>UTF-8</encoding>
        <nonFilteredFileExtensions>
            <nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
        </nonFilteredFileExtensions>
    </configuration>
</plugin>

注:此配置可以避免xlsx文件在resource目录下被自动压缩,这样就可以正常下载了。

②重新加载maven,再次下载文件,问题解决

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值