我把模板文件放在了资源目录下
当maven插件打包项目时,缺省情况下会压缩资源目录下的文件。
服务器读取的文件流来自压缩文件,但返回浏览器时,浏览器无法将他解析为正常文件并获得正确的结果。
解决方案:
配置maven插件,以在打包时不压缩模板文件,并消除解压缩名为xlsx的文件。
plugingroupidorg.Apache.maven.plugins/groupidartifactidmaven-resources-plugin/artifactidconfigurationencodingutf encodingnonfilteredfileextensionsnonfilteredfileextensionxlsx/nonfilteredfileeeextension/ngution
要彻底解决乱码问题,需要在代码中做一些处理。
在下面贴上工具类,看看大致的想法就可以了。
package com.zikoo.czjlk.utils; import com.zi koo.czjlk.exception.emservererror; import com.zi koo.czjlk.exception.emserverexception; import javax.servlet.http.http无servlet保罗; import java.io.*; import java.net.URLEncoder; 公共类文件{ publicstaticvoiddownload (httpservletresponseresponse,String filePath,String fileName ) try { response } response.setheader (' content-disposition ',' attachment; filename=' urlencoder.encode (filename,' UTF-8 ' ); inputstream is=thread.current thread (.getcontextclassloader ).getresourceasstream ) )文件路径); witebytes(is,response.getOutputStream ) ); }catch(exceptione ) thrownewemserverexception ) emservererror.file _ operation _ error ); 私有流操作系统try{byte[]buf=newbyte(1024 ); int len=0; while((len=is.read ) ) buf )!=-1 ) OS.write(buf,0,len ); }catch(exceptione ) thrownewemserverexception ) emservererror.file _ operation _ error ); (Finally ) if(is!=null () try ) is.close ); }catch(ioexceptione ) { e.printStackTrace ); } If (操作系统!=null () try ) OS.close ); }catch(ioexceptione ) { e.printStackTrace ); } } } }}