Issue
I am downloading a file on my server to the local machine that is running the XPage. However, when I call the method in my Java bean that facilitates this I receive the Error: java.lang.IllegalStateException: Can't get a Writer while an OutputStream is already in use
XPage Code
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
<xp:br></xp:br>
<xp:br></xp:br>
<xp:br></xp:br>
<xp:button value="Download Test" id="button1">
<xp:eventHandler event="onclick" submit="true"
refreshMode="complete">
<xp:this.script><![CDATA[#{javascript:FileDownload.sendFile("//local//notesdata//Shared//AFS//test.pdf");}]]></xp:this.script>
</xp:eventHandler></xp:button></xp:view>
Java Bean Code
package pdf;
import java.io.*;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;
public class FileDownload
{
public void sendFile(filePath)
{
File file = new File(filePath);
if (file.exists()) {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
HttpServletResponse response = (HttpServletResponse) ec.getResponse();
response.setContentType("application/pdf"); // figure out the type from extension or else
OutputStream out;
try {
// for the download dialog
response.setHeader("Content-disposition","attachment; filename*=utf-8''" + java.net.URLEncoder.encode(file.getName(), "UTF-8").replace("+", "%20"));
out = response.getOutputStream();
FileInputStream in = new FileInputStream(file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.flush();
} catch (IOException e) {
}
}
}
}
Solution
Try adding FacesContext.getCurrentInstance().responseComplete();
before you close/flush the OutputStream.
Answered By - Per Henrik Lausten
Answer Checked By - Marilyn (JavaFixing Volunteer)