HttpServletResponse getOutputStream在csv文件上发送html代码

时间:2016-09-12 18:56:18

标签: java spring weblogic

我正在尝试下载csv文件,但html代码(页眉和页脚)也会发送到该文件中。我正在使用weblogic,但是使用tomcat工作正常。代码如下:

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);
        }
    }

谢谢!

2 个答案:

答案 0 :(得分:1)

我的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();
    }
}

答案 1 :(得分:1)

设置ContentLength有效!因为ContentLength现在是csvFile.length(),所以不再需要额外的数据。谢谢!