-1
I am trying to download a file. CSV that I have saved. However the download does not appear to me when I click the button and no error code appears.
How can I test to see how far the procedure is being performed?
Follows the code:
@RequestMapping(value = { "/gerarCsv/" })
@ResponseBody
public void gerarCsv(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "inicio", required = true) String inicio,
@RequestParam(value = "fim", required = true) String fim) {
try {
Date dataInicio = new SimpleDateFormat("dd-MM-yyyy").parse(inicio);
Date dataFim = new SimpleDateFormat("dd-MM-yyyy").parse(fim);
List<RevogacaoConsolidado> revogacaoConsolidado = revogacao.consultarRevogacaoconsolidado(dataInicio,
dataFim);
File arquivo = new File(context.getRealPath("WEB-INF/classes/statics/downloads/revogacao.csv"));
logger.info("[Recurso:/admin/revogacao/revogacaoPorDataCSV, sessao:" + request.getSession().getId()
+ ", usuario:" + request.getUserPrincipal().getName() + "]" + "[Caminho ]" + arquivo);
// Cria arquivo caso não exista.
if (!arquivo.exists()) {
arquivo.createNewFile();
}
/*
* Escreve o arquivo e guarda dentro do caminho desejado objeto arquivo
*/
FileWriter fw = new FileWriter(arquivo);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Data" + ";" + "Login" + ";" + "Nome" + ";" + "Sucesso" + ";" + "Erro" + ";" + "Não Cadastrado"
+ ";" + "Já removido" + ";" + "Total" + ";" + "Porcentagem de Erro %");
for (RevogacaoConsolidado revog : revogacaoConsolidado) {
bw.newLine();
bw.write(revog.getData_processo() + ";" + revog.getLogin() + ";" + revog.getNome() + ";"
+ revog.getSucesso() + ";" + revog.getErro() + ";" + revog.getNao_cadastrado() + ";"
+ revog.getJa_removido() + ";" + revog.getTotal() + ";" + revog.getPorcentagem_erro());
}
bw.close();
fw.close();
/*
* realiza o download do conteudo.
*/
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=revogacao.csv");
response.setContentLengthLong((int) arquivo.length());
FileInputStream fileIn = new FileInputStream(arquivo);
ServletOutputStream out = response.getOutputStream();
try {
byte[] outputByte = new byte[4096];
int lidos = -1;
while ((lidos = fileIn.read(outputByte)) != -1) {
out.write(outputByte, 0, lidos);
}
fileIn.close();
out.flush();
out.close();
System.out.println("Download de arquivo");
logger.info("[Recurso:/admin/revogacao/revogacaoPorDataCSV, sessao:" + request.getSession().getId()
+ ", usuario:" + request.getUserPrincipal().getName() + "]"
+ "[Verificação de Revogações por data de processado CSV ] [download de arquivo Realizado]");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
logger.info("[Recurso:/admin/revogacao/revogacaoPorDataCSV, sessao:" + request.getSession().getId()
+ ", usuario:" + request.getUserPrincipal().getName() + "]"
+ "[Verificação de Revogações por data de processado CSV ]");
} catch (Exception e) {
logger.info("[Recurso:/admin/revogacao/revogacaoPorDataCSV, sessao:" + request.getSession().getId()
+ ", usuario:" + request.getUserPrincipal().getName() + "]"
+ "[Verificação de Revogações por data de processado] error: " + e);
}
}
Note: Checking the Chrome console, in the Network tab, I see that the request was made and the method successfully called, was generated until a Replay with the generated data. When I see in Timing I see that there was a time for content Download. It should not be being performed to download the file?
In this case, my Write is inside While, if you observe while ((read = fileIn.read(outputByte)) != -1) { out.write(outputByte, 0, read); }
– Willian Lima
But you need to write in Sponse to download the file from the browser. The
OutputStream
that I refer to is thegetOutputStream()
ofHttpServletResponse response
– jotape
I understand, but I’m doing this procedure only separately. in the case my OUT object corresponds to the Response.getOutputStream() and inside While is where I use Write()
– Willian Lima
just as an addition. When I check Response within Network -> my function -> Response. I see that the data he searched is there, instead of downloading the file.
– Willian Lima