JavaBean 中的 XPages HttpServletResponse 错误

XPages HttpServletResponse Error In JavaBean

我正在将我服务器上的一个文件下载到本地计算机,即 运行 XPage。但是,当我在我的 Java bean 中调用有助于此的方法时,我收到错误: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) {

            }
        }
    }
}

尝试在 close/flush OutputStream 之前添加 FacesContext.getCurrentInstance().responseComplete();