在 p:ajax rowSelect 事件期间下载文件 p:dataTable.



我想通过行单击素数数据表来下载文档文件。我尝试使用 ajax 从 Bean 调用操作,如下所示:

<p:dataTable
id="docId"
value="#{testBean.document}"
var="doc"
selectionMode="single"
selection="#{testBean.selectedDoc}"
>
<p:ajax event="rowSelect" listener="#{testBean.actionDownload}"/>
<p:column>
...
</p:column>
...
</p:dataTable>

但是下面的代码没有执行我想要的。我行动的逻辑是正确的。但似乎下载文档不适用于 ajax 请求。没有反应,下载未执行。

public String actionDownload() {
try {
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
StringBuffer contentDisposition = new StringBuffer();
contentDisposition.append("attachment;");
contentDisposition.append("filename="");
contentDisposition.append(name);
contentDisposition.append(""");
response.reset();
response.setContentType("application/x-download");
response.setHeader("Content-Disposition", contentDisposition.toString());
ServletOutputStream out = response.getOutputStream();
response.setContentType("application/x-download");
out.write(output);
out.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
FacesContext.getCurrentInstance().responseComplete();
return null;
}

是否有通过单击数据表行下载文件的替代方法?

您无法使用 JSF/PrimeFaces Ajax 下载文件。改为使其成为非 Ajax 请求。

<p:ajax>中的 ajax 侦听器替换为 GET 请求,如下所示oncomplete

<p:ajax event="rowSelect" oncomplete="window.location='#{request.contextPath}/download/#{doc.id}'"/>

并用普通的 Servlet 替换actionDownload()的背靠 bean 方法,如下所示:

@WebServlet("/download/*")
public class Download extends HttpServlet {
@Inject
private DocumentService service;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Document document = service.find(Long.valueOf(request.getPathInfo().substring(1)));
response.setContentType(getServletContext().getMimeType(document.getFileName()));
response.setContentLength(document.getContent().length);
response.setHeader("Content-Disposition", "attachment;filename="" + URLEncoder.encode(document.getFileName(), "UTF-8") + """);
response.getOutputStream().write(document.getContent());
}
}

相关内容

  • 没有找到相关文章

最新更新