我试图通过 JSF 实现相同的下载文件,如这些帖子中所述: JSF2 下载文件返回 xhtml 页面源 如何从 JSF 支持 bean 提供文件下载? http://bharatonjava.wordpress.com/2013/02/01/downloading-file-in-jsf-2/ http://prabinhada.blogspot.com/2012/06/how-to-download-file-using- jsf.html
我的问题是我实际上可以下载该文件,但它的名称是错误的(在任何浏览器上)。这是我在下载方法中编组的 XML 文件,但浏览器总是收到文件 index.jsf(但 mime 类型设置为 text/xml 并且文件大小正确)
它运行在:
- 莫哈拉 2.1.7
- Richfaces 4.3.3.Final
- jboss-7.1.1.Final
如果您发现任何问题,请参阅下文
public void exportEDL() throws Exception {
String name = this.file.getName();
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
BufferedOutputStream output = null;
StringWriter sw = null;
try {
...
sw = new StringWriter();
// edl is the jaxb i want to return as xml file
marshaller.marshal(this.edl, sw);
// Init servlet response.
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType("text/xml");
response.setContentLength( sw.getBuffer().length() );
response.setHeader("Content-Disposition", "attachment;filename\"" + name + "\"");
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
output.write(sw.toString().getBytes("UTF-8"));
// Finalize task.
sw.flush();
output.flush();
} catch ( Exception e ) {
FacesMessage msg = new FacesMessage( FacesMessage.SEVERITY_ERROR, null, e.getMessage() );
facesContext.addMessage("Error", msg);
return;
} finally {
// Gently close streams.
IOUtil.close(sw);
IOUtil.close(output);
clearUploadData();
}
// Inform JSF that it doesn't need to handle response.
facesContext.responseComplete();
// facesContext.renderResponse();
// facesContext.release();
}
我尝试了除 XML 编组之外的其他方法,但没有更好的结果。你们是否设法下载了具有正确名称+扩展名的文件?
它是视图中的命令按钮:
<h:commandButton action="#{fileUploadBean.exportEDL()}"
谢谢!