如果附件文件大小超过 16363 字节,Content-Disposition 不会在 Spring 引导应用程序中响应

If attachment file size is more than 16363byte Content-Disposition is not comming in response in Spring boot application

如果附件文件大小超过 16363 字节,Content-Disposition 不会在 Spring 启动应用程序中响应。

我使用 Java 8 和 Spring 引导 我需要发送带有特殊文件名的 zip 文件。

HttpServletResponse response;

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
ZipOutputStream zip = new ZipOutputStream(byteArrayOutputStream);
zip.putNextEntry(new ZipEntry(foldername));
objectMapper.writerWithDefaultPrinter().writeValue(zip, list);
zip.closeEntry();
byteArrayOutputStream.writeTo(responseOutputStream);

ContentDisposition contentDisposition = ContentDisposition.type("attachment").fileName(fileName).build()
response.addHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());

我不想使用像 File file = createTempCSVFile(); 这样的解决方案,因为我总是需要控制附件文件。

响应 header 必须在响应 body 之前发送。 Spring 和 servlet 容器尝试缓冲输出流,以便您可以延迟指定响应 header,但是 - 正如您所注意到的 - 此缓冲区是有限的。

您可以通过在开始写入输出流之前提供响应 header 轻松解决问题:

ContentDisposition contentDisposition = ContentDisposition.type("attachment").fileName(fileName).build()
response.addHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
ZipOutputStream zip = new ZipOutputStream(byteArrayOutputStream);
zip.putNextEntry(new ZipEntry(foldername));
objectMapper.writerWithDefaultPrinter().writeValue(zip, list);
zip.closeEntry();
byteArrayOutputStream.writeTo(responseOutputStream);