栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

Java解决服务器下载excel文件提示损坏无法打开的问题

Java解决服务器下载excel文件提示损坏无法打开的问题

一开始通过请求的方式写了个下载文件的工具代码,可以参考下面链接
https://blog.csdn.net/z2014ypd/article/details/88417757
这种方式在项目打包发布后,获取的文件是提示损坏,无法打开的,原因就是项目打包,不会将resources文件夹下面的资源一起打包,而且打包的时候maven会对文件进行压缩,这就导致请求响应访问错误,文件自然就是损坏的。
解决资源打包以及压缩问题,只需要在打包的pom里面增加配置


        
        		//这个插件是为了防止打包的时候压缩xlsx类型的文件
            
                org.apache.maven.plugins
                maven-resources-plugin
                
                    UTF-8
                    
                        xlsx
                    
                
            
        
        
        	//这个是说明文件放的地址,资源文件位置,打包的时候才会把资源文件打包放到jar包里面
            
                src/main/java
                
                    ***.xml
                    ***.yml
                    ***.xlsx
                
            
        
    

进行配置之后,就是使用文件流的方式读取文件,进行下载。因为Linux都是读取文件流,这个方式之外的都不行,都会乱码。参考工具代码如下:

public static void download(HttpServletResponse response, String filePath, String fileName){
        try {
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
            InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
            writeBytes(is, response.getOutputStream());
        }catch (Exception e) {
           e.printStackTrace();
        }
    }

    private static void writeBytes(InputStream is, OutputStream os) {
        try {
            byte[] buf = new byte[1024];
            int len = 0;
            while((len = is.read(buf))!=-1)
            {
                os.write(buf,0,len);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

这样操作之后,就可以打包,下载jar包内的文件到本地打开了

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/748158.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号