我在使用 Struts2 下载文件时遇到问题。我做了一堆研究并发现了一堆类似的问题,但没有一个答案对我有帮助。
这是我目前拥有的
JSP
<s:url id="fileDownload" namespace="/jsp" action="download"></s:url>
Download file - <s:a href="%{fileDownload}">MyFile.pdf</s:a>
Action
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>
当我单击该链接时,它会下载一个名称正确的文件,但其中没有任何数据。如果有人对我做错了什么有任何想法,我很乐意提出建议,因为我确信这只是一些愚蠢的事情。
最佳答案
我找到了答案。您必须在 struts 中定义内容长度。为此,我执行了以下操作:
Struts.xml
<param name="contentLength">${contentLength}</param>
Action
private long contentLength;
public long getContentLength() {
return contentLength;
}
public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}
在执行()
contentLength = fileToDownload.length();
关于java - Struts 2 下载文件为 0 字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38531702/