我正在尝试使用PrimeFaces commandButton下载文件。该操作将调用该方法,但下载不会开始。从本地html或URL调用该方法时,下载开始。 有什么方法可以直接使用JSF下载吗?
这是我的表格:
<h:form id="form">
<h:panelGrid columns="6" cellpadding="5">
<p:commandButton value="Download" action="#{jobsView.downloadTest()}"/>
</h:panelGrid>
</h:form>
控制器中的方法(ViewScoped):
public void downloadTest() {
restService.downloadTest();
FacesContext.getCurrentInstance().responseComplete();
}
REST服务中的方法:
@RequestMapping("/downloadTest")
public ResponseEntity<Resource> downloadTest() {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, "application/ms-excel;
charset=" + CHARSET);
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;
filename=" + LocalDateTime.now() + "_PrintJob.csv");
StringBuilder sb = new StringBuilder();
sb.append(JobTrackingUtil.PRINTJOB_CSV_HEADER);
System.out.println("Downlaod started");
ByteArrayResource resource = new ByteArrayResource(sb.toString().getBytes());
return ResponseEntity.ok().headers(headers).contentLength(resource.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream")).body(resource);
}