使用注释在Struts 2中下载文件

时间:2012-12-20 13:29:08

标签: struts2 annotations download

我想问一下是否有人可以帮助我使用Struts 2注释下载文件的示例

我在动作类

中尝试了这个
public class MyClass {
private InputStream       fileInputStream;

    private String      fileName;

    @Override
    @Action(AbstractBasisAction.VIEW)
    public String view() {
    System.out.println("HoursCycleDownloadFrameAction: view");
    super.view();
    return SUCCESS;
    }

    public InputStream getFileInputStream() {
    return fileInputStream;
    }

    @Action(value = "downloadFile", results = { @Result(name = "success", type = "stream", params = { "contentType", "application/octet-stream", "inputName", "fileInputStream", "contentDisposition", "filename=\"${fileName}\"", "bufferSize", "1024" }) })
    public String downloadFile() throws Exception {
    fileName = "license.txt";
    fileInputStream = new FileInputStream(new File("C:\\", fileName));
    return SUCCESS;
    }
}

这就是我的页面包含的内容

<s:url id="fileInputStream" namespace="/myClass" action="downloadFile" ></s:url>

Download file - <s:a href="%{fileInputStream}">lisence.txt</s:a>

但现在问题是它使用操作方法名称下载文件。表示文件名是downloadFile.action。任何人都可以帮我吗?

1 个答案:

答案 0 :(得分:0)

1)如果是.txt文件,"contentType", "application/octet-stream" 应改为"contentType", "plain/text";

2)你需要一个private String fileName;变量的吸气剂;

3)"contentDisposition", "filename=\"${fileName}\""应包含扩展名,最终inline(默认,在浏览器中打开)或attachment(询问是否下载或打开客户端应用程序),例如

"contentDisposition", "attachment; filename=\"${fileName}.txt\""