Spring MVC 文件下载过程中 出现下载文件乱码

来源:互联网 发布:淘宝外卖粮票怎么获得 编辑:程序博客网 时间:2024/05/16 09:09

在使用一个框架时,程序员分为三种级别 
1.看demo开发 
2.看文档开发 
3.看源码开发 

明显1不如2,2不如3 
但是考虑时间成本3不如2,2不如1 

我的原则是 
有好的demo不看文档,有好的文档不看源码 

对于文件下载,再简单不过了,但我比较傻,不会自己写 
于是在google搜索"Spring mvc 3 download",demo版本都差不多 

Java代码    收藏代码
  1. @RequestMapping("download")  
  2. public void download(HttpServletResponse res) throws IOException {  
  3.     OutputStream os = res.getOutputStream();  
  4.     try {  
  5.         res.reset();  
  6.         res.setHeader("Content-Disposition""attachment; filename=dict.txt");  
  7.         res.setContentType("application/octet-stream; charset=utf-8");  
  8.         os.write(FileUtils.readFileToByteArray(getDictionaryFile()));  
  9.         os.flush();  
  10.     } finally {  
  11.         if (os != null) {  
  12.             os.close();  
  13.         }  
  14.     }  
  15. }  



因为鄙人强烈的精神洁癖,心中大骂 
“这样的狗屁代码也贴在网上?” 

既然使用了mvc,怎么还能暴露HttpServletResponse这样的j2ee接口出来! 

我相信spring提供了更好的方式,于是开始翻阅文档,得出如下代码 

Java代码    收藏代码
  1. @RequestMapping("download")  
  2. public ResponseEntity<byte[]> download() throws IOException {  
  3.     HttpHeaders headers = new HttpHeaders();  
  4.     headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);  
  5.     headers.setContentDispositionFormData("attachment""dict.txt");  
  6.     return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(getDictionaryFile()),  
  7.                                       headers, HttpStatus.CREATED);  
  8. }  



理论上没问题,实现上很优雅 
但是文件下载后内容如下 

Java代码    收藏代码
  1. "YWEJMQ0KdnYJMg0KaGgJMw=="  



正确内容为 

Java代码    收藏代码
  1. aa  1  
  2. vv  2  
  3. hh  3  



我把代码改为 

Java代码    收藏代码
  1. ResponseEntity<String>  



输出如下 

Java代码    收藏代码
  1. "aa    1\n\tvv     2\n\thh  3"  



相信很多人看到这已经知道了发生了什么 
但是因为本人狗屎一样的基础知识,又浪费了几小时 

先去看了ByteArrayHttpMessageConverter的源码 

Java代码    收藏代码
  1.        public ByteArrayHttpMessageConverter() {  
  2.     super(new MediaType("application""octet-stream"), MediaType.ALL);  
  3. }  
  4.        ...  
  5.        protected void writeInternal(byte[] bytes, HttpOutputMessage outputMessage) throws IOException {  
  6.     FileCopyUtils.copy(bytes, outputMessage.getBody());  
  7. }  


没感觉到有任何问题 

捉耳挠腮了一阵子,又去看AnnotationMethodHandlerAdapter 

Java代码    收藏代码
  1.       public AnnotationMethodHandlerAdapter() {  
  2. // no restriction of HTTP methods by default  
  3. super(false);  
  4.   
  5. // See SPR-7316  
  6. StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();  
  7. stringHttpMessageConverter.setWriteAcceptCharset(false);  
  8. //这里有默认值  
  9.               this.messageConverters = new HttpMessageConverter[]{new ByteArrayHttpMessageConverter(), stringHttpMessageConverter,  
  10.         new SourceHttpMessageConverter(), new XmlAwareFormHttpMessageConverter()};  
  11.   
  12.         
  13.       //set时默认值全被取消了  
  14.       public void setMessageConverters(HttpMessageConverter<?>[] messageConverters) {  
  15. this.messageConverters = messageConverters;  



再去看MappingJacksonHttpMessageConverter 

Java代码    收藏代码
  1. extends AbstractHttpMessageConverter<Object>//Object是万用的,就想Exception类型,优先级别应该最低  



突然有一种自己是个傻 逼的感觉,浪费了大概3、4个小时 

修改xml 

Java代码    收藏代码
  1. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
  2.     <property name="messageConverters">  
  3.         <list>  
  4.             //把ByteArray加在Json前面  
  5.             <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>  
  6.             <bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >  
  7.                 <property name = "supportedMediaTypes">  
  8.                     <list>  
  9.                         <value>text/plain;charset=UTF-8</value>  
  10.                     </list>  
  11.                 </property>  
  12.             </bean>  
  13.         </list>  
  14.     </property>  
  15. </bean>  



终于如我所愿了 

记录一下我这几个小时干的蠢事 
顺便想说,每个例子和demo最好都以最佳实践去写 
这样我这种菜鸟程序员就没机会去看源码了~ 

 

http://www.iteye.com/topic/1125784

0 0
原创粉丝点击