Bom, eu tenho uma aplicação rodando e em determinado momento o usuario gera um arquivo .zip e ele precisa baixar esse arquivo, a minha pergunta é:
Como eu faço pra ele gerar o arwuivo e enviar o mesmo na resposta para o usuario?
Sei que tenho que usar o HttpServletRequest e ttpServletResponse, porem não sei como usalos, alguem poderia me dar uma luz?
Meu codigo esta assim:
publicvoidcriaArquivoZip()throwsZipException,IOException{try{Filefile=newFile("C:/Users/Apanhamentos/Documents/workspace/Administracao/"+nomeZip);ziper.criarZip(file,list);//aqui ele deveria enviar o arquivo para o usuario...}catch(Exceptione){// TODO: handle exceptione.printStackTrace();}}
FacesContextfacesContext=FacesContext.getCurrentInstance();HttpServletRequestrequest=(HttpServletRequest)facesContext.getExternalContext().getRequest();HttpServletResponseresponse=(HttpServletResponse)facesContext.getExternalContext().getResponse();OutputStreamos=null;try{
os=response.getOutputStream();response.setContentType("application/zip");response.setContentLength(ARQUIVO.length);response.setHeader("Content-disposition","attachment; filename=\"arquivo.zip\"");os.write(ARQUIVO);//pegar seu arquivo zip gerado e converte-lo em byte[]}catch(Exceptione){
e.printStackTrace();}finally{
try{
if(os!=null){
os.flush();os.close();}
facesContext.responseComplete();}catch(IOExceptione){
e.printStackTrace();}
}
t+
ArthurTurtle
Puts valeu cara funciona que é uma beleza, o codigo pra que quiser ver fico assim:
publicvoidcriaArquivoZip()throwsZipException,IOException{try{FilefileGerado=newFile(caminho+nomeZip);ziper.criarZip(fileGerado,list);FacesContextfacesContext=FacesContext.getCurrentInstance();HttpServletRequestrequest=(HttpServletRequest)facesContext.getExternalContext().getRequest();HttpServletResponseresponse=(HttpServletResponse)facesContext.getExternalContext().getResponse();OutputStreamos=null;System.out.println();byte[]arquivoGerado=recuperaFileEmByte(fileGerado);try{os=response.getOutputStream();response.setContentType("application/zip");response.setContentLength(arquivoGerado.length);response.setHeader("Content-disposition","attachment; filename=\"arquivo.zip\"");os.write(arquivoGerado);//pegar seu arquivo zip gerado e converte-lo em byte[] }catch(Exceptione){e.printStackTrace();}finally{try{if(os!=null){os.flush();os.close();}facesContext.responseComplete();}catch(IOExceptione){e.printStackTrace();}}nomeZip="";}catch(Exceptione){// TODO: handle exceptione.printStackTrace();}}privatebyte[]recuperaFileEmByte(FileinFile){InputStreamis=null;byte[]buffer=null;System.out.println(inFile.getAbsolutePath());try{is=newFileInputStream(inFile);buffer=newbyte[is.available()];is.read(buffer);is.close();}catch(FileNotFoundExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}returnbuffer;}
Vlww
A
alissonvla
cara,
so mais uma dica, vc nem precisa salvar o arquivo fisicamente, vc pode criar seu arquivo zip e pegar o byte[].