Java HttpServletResponse getOutputStream在csv文件上发送html代码
我试图下载一个csv文件,但html代码(页眉和页脚)也被发送到该文件中。我使用的是weblogic,但使用tomcat很好。代码如下:Java HttpServletResponse getOutputStream在csv文件上发送html代码,java,spring,weblogic,Java,Spring,Weblogic,我试图下载一个csv文件,但html代码(页眉和页脚)也被发送到该文件中。我使用的是weblogic,但使用tomcat很好。代码如下: public void downloadCSVReport(String csvFile, HttpServletResponse response){ try { response.setHeader("Content-Disposition", "attachment; filename=example.csv")
public void downloadCSVReport(String csvFile, HttpServletResponse response){
try {
response.setHeader("Content-Disposition", "attachment; filename=example.csv");
response.setContentType("text/csv");
ByteArrayInputStream bais = new ByteArrayInputStream(csvFile.toString().getBytes(REPORT_ENCODING));
IOUtils.copy(bais, response.getOutputStream());
response.flushBuffer();
} catch( IOException e ){
LOGGER.error(e.getMessage(), e);
}
}
谢谢 我的Spring webapp中的这段代码有效
public static void putFileInResponse(HttpServletResponse response, File file, String contentType) throws IOException {
// Set the headers
response.setContentType(contentType);// "application/octet-stream" for example
response.setContentLength((int) file.length());
response.addHeader("Content-Disposition", new StringBuilder("attachment; filename=\"").append(file.getName()).append("\"").toString());
response.addHeader("Content-Description", "File Transfer");
response.addHeader("Content-Transfer-Encoding", "binary");
response.addHeader("Expires", "0");
response.addHeader("Cache-Control", "no-cache, must-revalidate");
response.addHeader("Pragma", "public");
response.addHeader("Content-Transfer-Encoding", "binary");
// Write the content of the file in the response
try (FileInputStream fis = new FileInputStream(file); OutputStream os = response.getOutputStream()) {
IOUtils.copyLarge(fis, os);
os.flush();
}
}
设置ContentLength有效!额外的数据不再重要,因为ContentLength现在是csvFile.length()。谢谢