首页 > 解决方案 > 使用tomcat时如何将文件保存在客户端电脑而不是服务器电脑上

问题描述

我有一个使用 POI 保存 xlsx 的服务,当我将文件保存到它保存在服务器 pc 上而不是客户端 pc 上的路径时。

我的程序的部分代码:

public static final String EXCELPATH = "C:\\SAMPLE\\REPORTS\\";

Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet 1");

filepath = EXCELPATH + "TCRKBOS_050020_" + mTodayDate;
FileOutputStream fileOut = new FileOutputStream(filepath + ".csv");
Row row;
Cell cell;

// ********* SAMPLE CELL **************** //
row = sheet.createRow(0);
cell = row.createCell(0);
cell.setCellValue("REPDTE");
cell.setCellStyle(centerHeader1);

cell = row.createCell(1);
cell.setCellValue("BNKCDE");
cell.setCellStyle(centerHeader1);

conn.close();
wb.write(fileOut);
fileOut.flush();
fileOut.close();

标签: javajsptomcat

解决方案


您无法在客户端 PC 上保存文件。它是管理文件是否下载到客户端 PC 上的浏览​​器。

您可以做的是通过 HTTP 发送文件作为您的响应。我假设您在这里使用的是 Servlet。在您的 servlet 中,如果您希望文件下载响应 GET 请求,您可以执行以下操作:

  protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException {

        resp.setContentType("text/csv");
        resp.setHeader("Content-disposition", "attachment; filename=TCRKBOS_050020_" + mTodayDate + ".csv");

        try (OutputStream out = resp.getOutputStream()) {
            //todo: write the CSV data to the output stream
        }
    }

推荐阅读