spring-mvc下载动作

有没有一些技巧让SpringMVC自定义视图在浏览器中下载文件? 我已经从org.springframework.web.servlet.View实现了render方法,但是代码导致我的数据被作为数据blob写入页面,而不是启动下载操作。

 try { Document oDoc = (Document) model.get("oDoc"); out = new PrintWriter(response.getOutputStream()); response.setContentType("application/vnd.ms-excel"); response.setHeader("content-disposition", "attachment; filename=file.xls"); GenerateXLSFile gof = new GenerateXLSFile(); gof.outputTSVFromDom(out, oDoc); } catch block here { //writes to log here } finally { if (out != null) { out.flush(); out.close(); } } 

我知道从服务器日志中调用渲染方法。 我知道GenerateXLSFile正在从服务器日志中创build。 我知道outputTSVFromDom可以接受一个文档,并从我的JUnittesting中转换它。 它也写入服务器日志并完成。 数据在浏览器中结束。 根据萤火虫HTTP头看起来很正常。 catch块中没有错误在服务器日志中。

我在这里错过了什么?

首先,你使用哪个API? Excel文档是二进制的,所以你应该使用OutputStream,而不是Writer。

其次,Spring有一个内置的支持Excel文档的服务:

  • AbstractExcelView ,基于Apache POI API
  • AbstractJExcelView ,基于JExcel API