我尝试使用JSF下载文件,方法是在运行程序时将表属性作为路径,它运行正常一次,然后错误来到HTTP状态404 ...我该怎么做才能下载文件?
XHTML代码
<p:dataTable id="idAttachmentTable" var="attach"
value="#{documentMB.attachList1}"
selectionMode="single"
selection="#{documentMB.selectedAttachment}"
rowKey="#{attach.attachmentId}">
<f:facet name="header">
Attachments
</f:facet>
<p:column headerText="#{bundle.subject}">
<h:outputText value="#{attach.attachName}" />
</p:column>
<p:column>
<h:commandLink id="getDownload" value="#{attach.attachName}" action="#{documentMB.downLoad}">
<f:setPropertyActionListener target="#{documentMB.selectedAttachment}" value="#{attach}" />
</h:commandLink>
</p:column>
</p:dataTable>
documentMb.java
private static final int DEFAULT_BUFFER_SIZE = 10240;
private String filePath = "C:\\temp\\123.PNG";
public void downLoad() throws IOException {
System.out.println("in download");
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
System.out.println("after Faces");
System.out.println(filePath);
System.out.println(selectedAttachment.getAttachmentName());
java.io.File file = new java.io.File(selectedAttachment.getAttachmentName());
System.out.println(selectedAttachment.getAttachmentName());
if (!file.exists()) {
System.out.println(selectedAttachment.getAttachmentName());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType("application/octet-stream");
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment;filename=\"" + file.getName() + "\"");
System.out.println(file.getName());
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
input.close();
output.close();
}
context.responseComplete();
}