我正在使用jdev 11.1.1.5.0.
。在我的用例中,我想创建一个下载链接。当用户单击链接时,该文件应自动下载(如下载servlet)。
代码如下:
HttpServletResponse response= (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse(); response.setContentType("text/plain"); response.setHeader("Content-Disposition","attachment;filename="+part.getFileName()); response.setContentType("text/plain"); response.setHeader("ContentDisposition","attachment;filename="+part.getFileName()); InputStreaminput=part.getInputStream(); int read=0;
byte[] bytes = new byte[1024]; OutputStream os =response.getOutputStream();
while((read=input.read(bytes))!=-1)
{os.write(bytes, 0, read);
}
os.flush();
os.close();
但它不起作用。我的要求是想要创建动态链接(URL),当用户点击链接时,文件就会被下载。有没有其他方法可以做到这一点?感谢。
答案 0 :(得分:0)
创建commandLink并向其提供File Download Action Listener并向该侦听器提供代码
<af:commandButton text="Say Hello">
<af:fileDownloadActionListener filename="hello_txt"
contentType="text/plain; charset=utf-8"
method="#{bean.sayHello}"/>
</af:commandButton>
public void sayHello(FacesContext context, OutputStream out) throws IOException
{
OutputStreamWriter w = new OutputStreamWriter(out, "UTF-8");
w.write("Hi there!");
// The stream is automatically closed, but since we wrapped it,
// we'd better flush our writer
w.flush();
}