Struts 2 下载文件为 0 字节

Struts 2 Download File is 0 bytes

我在使用 Struts2 下载文件时遇到问题。我做了很多研究并发现了很多类似的问题,但是 none 的答案对我有所帮助。

这是我目前拥有的

JSP

<s:url id="fileDownload" namespace="/jsp" action="download"></s:url>
Download file - <s:a href="%{fileDownload}">MyFile.pdf</s:a>

操作

private InputStream inputStream;
private String fileName;
public String execute() throws Exception {
        File fileToDownload = new File("C:My Documents/MyFile.pdf");
        fileName = fileToDownload.getName();
        inputStream = new FileInputStream(fileToDownload);      
        return SUCCESS;
    }

public String getFileName() {
    return fileName;
}

public void setFileName(String fileName) {
    this.fileName = fileName;
}

public InputStream getInputStream() {
    return inputStream;
}

Struts.xml

<action name="download" class="com.my.path.to.action.class">
        <result name="success" type="stream">
                <param name="contentDisposition">attachment;filename=${fileName}</param>
                <param name="contentType">application/pdf</param>
                <param name="inputName">inputStream</param>
                <param name="bufferSize">4096</param>
        </result>
</action>

当我点击 link 时,它会下载一个正确命名的文件,但其中没有数据。如果有人对我做错了什么有任何想法,我很乐意提出建议,因为我确定这只是一些愚蠢的事情。

我找到了答案。您必须在 struts 中定义内容长度。为此,我执行了以下操作:

Struts.xml

<param name="contentLength">${contentLength}</param>

动作

private long contentLength;
public long getContentLength() {
    return contentLength;
}

public void setContentLength(long contentLength) {
    this.contentLength = contentLength;
}

在执行()

contentLength = fileToDownload.length();