如何让用户下载我的文件? (Java,MVC,Excel,POI)
我正在使用Struts2,Spring和Hibernate。
我用POI编写了一个名为test.xls的简单Excel文件。 当我运行该操作时,它的工作原理是因为test.xls出现,但是在我的tomcat文件夹中。
我希望该文件可以在我的jsp页面上下载。 如何让用户下载.xls文件? 相反,我该如何称呼该路径?
对不起,如果答案很明显,我是新手。 我知道它可能与ServletContext或HttpServletRequest有关吗?
[编辑]由于以下答案我得到了它。 这是工作代码:
private InputStream excelStream; public String export(){ //Create excelfile HSSFWorkbook workbook = new HSSFWorkbook(); FileOutputStream file = null; try{ file = new FileOutputStream("poi-test.xls"); } catch(IOException e){ e.printStackTrace(); } //Populate workbook with all the excel stuff ... //Write to file ByteArrayOutputStream baos = new ByteArrayOutputStream(); try{ workbook.write(file); workbook.write(baos); ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray()); excelStream = bis; } catch(IOException e){ e.printStackTrace(); } return "excel"; } public InputStream getExcelStream() { return excelStream; } public void setExcelStream(InputStream excelStream) { this.excelStream = excelStream; }
在我的struts文件中:
application/vnd.ms-excel excelStream attachment; filename="excelExport.xls" 1024
您想为此使用Struts2 Stream Result。 以下是一些相关信息:
- http://struts.apache.org/2.2.1/docs/ajax.html
- 如何在Struts2结果中返回excel?
- 使用Struts2的Stream Result
如果可以从Web服务器访问新创建的Excel文件,为什么不在JSP页面中将该HTTP链接呈现给Excel文件? 除非您想要动态流式传输excel文件,而不是像现在一样以物理方式创建它,否则这可能是最直接的解决方案。