1

I'm having an issue downloading a file using Struts2. I've done a pile of research and found a bunch of similar questions, but none of the answers have helped me out.

Here is what I currently have

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>

When I click on the link, it will download a file that's named correctly, but it has no data in it. If anyone has any ideas as to what I'm doing wrong, I would love a suggestion as I'm sure it's just something dumb.

ZaredH
  • 491
  • 1
  • 7
  • 23

1 Answers1

3

I found my answer. You must define the content length in struts. To do this I did the following:

Struts.xml

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

Action

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

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

in execute()

contentLength = fileToDownload.length();
ZaredH
  • 491
  • 1
  • 7
  • 23