我有控制器方法,一旦用户点击“下载”按钮就开始下载文件。对象列表可以包含大量最多400 000的对象。当我在csv文件中放入少量对象时 - 它工作正常。
@RequestMapping(value = "/downloadCSV")
public void downloadCSV(HttpServletResponse response) throws IOException
{
response.setContentType("text/csv");
String reportName = "metrics.csv";
response.setHeader("Content-disposition", "attachment;filename="+reportName);
ArrayList<String> rows = new ArrayList<String>();
rows.add("A, B, C, D, E");
rows.add("\n");
for (int i = 0; i < someList.size(); i++) {
String row = metricsDownloadModelList.get(i).getContentId()
+ someList.get(i).getA() + ", "
+ someList.get(i).getB() + ", "
+ someList.get(i).getC() + ", "
+ someList.get(i).getD() + ", "
+ someList.get(i).getE()
+ "\n";
rows.add(row);
}
Iterator<String> iter = rows.iterator();
while (iter.hasNext()) {
String outputString = (String) iter.next();
response.getOutputStream().print(outputString);
}
response.getOutputStream().flush();
}
但是当我将列表中的对象数量增加到1000或更多时,它就会出现。给我一个错误:
执行控制器时出错{org.apache.coyote.http11.HeadersTooLargeException:尝试将更多数据写入响应标头,而不是缓冲区中有可用空间。增加连接器上的maxHttpHeaderSize或将更少的数据写入响应头。
我可以在不修改servlet配置文件的情况下解决我的问题吗?还有其他方法可以解决这个问题吗?
答案 0 :(得分:0)
为了下载文件,我会执行以下操作:
为了做到这一点,我会写这种控制器:
@RequestMapping(method = { RequestMethod.GET }, value = { "/downloadCsv" })
public ResponseEntity<InputStreamResource> downloadCSV()
{
try
{
String fileName = "test.csv";
//Create here your CSV file
File theCsv = new File(fileName);
HttpHeaders respHeaders = new HttpHeaders();
MediaType mediaType = new MediaType("text","csv");
respHeaders.setContentType(mediaType);
respHeaders.setContentDispositionFormData("attachment", fileName);
InputStreamResource isr = new InputStreamResource(new FileInputStream(theCsv));
return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
}
catch (Exception e)
{
String messagge = "Error in CSV creation; "+e.getMessage();
logger.error(messagge, e);
return new ResponseEntity<InputStreamResource>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
通过使用这种控制器,我能够下载非常庞大的文件
安吉洛