Estou tento dificuldade para entender como obter um response e usar um stream através dele para enviar um arquivo !
Sempre obtenho o erro.
javax.servlet.ServletException: Servlet response already use Writer, OutputStream not possible
Segue o código …
public class Arquivo {
private List<Download> downloadList = new ArrayList<Download>();
private File[] fileList = new File("C:/Users/pirm/Downloads").listFiles();
public Arquivo() {
for (int i = 0; i < fileList.length; i++) {
Download download = new Download(fileList[i]);
downloadList.add(download);
}
}
public List<Download> getDownloadList() {
return downloadList;
}
public void setDownloadList(List<Download> downloadList) {
this.downloadList = downloadList;
}
}
public class Download {
private File file;
public Download(File file) {
this.file = file;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public synchronized void download() {
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setHeader("Content-Disposition", "attachment;filename=\"" + file.getName() + "\"");
response.setContentLength((int) file.length());
ServletOutputStream out = null;
try {
FileInputStream input = new FileInputStream(file);
byte[] buffer = new byte[1024];
out = response.getOutputStream();
int i = 0;
while ((i = input.read(buffer)) != -1) {
out.write(buffer);
out.flush();
}
FacesContext.getCurrentInstance().getResponseComplete();
} catch (IOException err) {
err.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException err) {
err.printStackTrace();
}
}
}
}
<h:form id="arquivos">
<rich:scrollableDataTable id="DataTableScrool" value="#{Arquivo.downloadList}" var="downloadItem"
frozenColCount="0"
first="0"
rows="40"
width="300px"
height="396px">
<rich:column width="50px">
<f:facet name="header" >
<h:outputText value="Download"/>
</f:facet>
<h:outputLink value="#{downloadItem.download()}">
<h:outputText value="Download"/>
</h:outputLink>
</rich:column>
<rich:column width="250px">
<f:facet name="header" >
<h:outputText value="Arquivo"/>
</f:facet>
<h:outputText value="#{downloadItem.getFile().getName()}">
<a4j:support event="onclick" reRender="DataTableScrool"/>
</h:outputText>
</rich:column>
</rich:scrollableDataTable>
</h:form>