Pregunta

I have used the code below for a csv file download

InputStream is = new ByteArrayInputStream(csv.toString().getBytes());
IOUtils.copy(is, response.getOutputStream());

response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment; filename=mycsvfile.csv");
response.flushBuffer();
is.close();

It worked fine for tens of records. I was able to download a *.csv file. But it returns text/plain with no file extension for hundreds of records.

¿Fue útil?

Solución

You're calling response.setHeader() after you've already sent the data to the response stream. If the response stream buffer wasn't big enough to handle all of that data, it would have to write the headers out in order to write the content. Frankly I'm surprised that setHeader isn't throwing an exception to say that the response body has already been started, but anyway...

Just move the header setting part to before the call to IOUtils.copy.

I would also strongly recommend specifying a character encoding in the String.getBytes() call, and specifying the same encoding in the response header. (I generally use UTF-8.)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top