如何让用户下载我的文件?(Java、MVC、Excel、POI) [英] How can I get the user to download my file? (Java, MVC, Excel, POI)

查看:18
本文介绍了如何让用户下载我的文件?(Java、MVC、Excel、POI)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Struts2、Spring 和 Hibernate.

I'm using Struts2, Spring, and Hibernate.

我编写了一个简单的 Excel 文件,名为 test.xls 和 POI.当我运行该操作时,它会起作用,因为 test.xls 出现了,但在我的 tomcat 文件夹中.

I have written a simple Excel file called test.xls with POI. When I run the action, it works because test.xls appears, but in my tomcat folder.

我希望可以在我的 jsp 页面上下载该文件.如何让用户下载 .xls 文件?相反,我该如何称呼这条路径?

I want that file to be downloadable on my jsp page. How do I go about getting the user to download the .xls file? Rather, how do I call that path?

对不起,如果答案很明显,我是新手.我知道它可能与 ServletContext 或 HttpServletRequest 有关?

Sorry if the answer is obvious, I am new to this. I know it probably has something to do with the ServletContext or HttpServletRequest?

[edit] 由于以下答案,我让它工作了.这是工作代码:

[edit] I got it working thanks to the below answers. Here is the working code:

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 文件中:

Over in my struts file:

        <result name="excel" type="stream">
            <param name="contentType">application/vnd.ms-excel</param>
            <param name="inputName">excelStream</param>
            <param name="contentDisposition">attachment; filename="excelExport.xls"</param>
            <param name="bufferSize">1024</param>
        </result>

推荐答案

您想为此使用 Struts2 Stream Result.以下是一些相关信息:

You want to use the Struts2 Stream Result for this. Here is some information on that:

这篇关于如何让用户下载我的文件?(Java、MVC、Excel、POI)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆