java - 使用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();
解决方案
您无法在客户端 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
}
}
推荐阅读
- python - 将文本/字符串转换为 python 数据框的数字/int
- gcc - 为什么 /arch/arm/cpu/armv7m/start.s 中的代码很少?是否完整?
- java - 如何创建多模块 Spring Boot Maven 项目?
- python - 多处理 ctypes.windll.kernel32.SetConsoleTitleW 计数器问题
- swift - 如何将领域结果对象分配给变量。类类型
- r - 参数估计
- python - 了解 Tello Drone 的代码
- javascript - 一段时间后运行命令(js)
- html - 使用 CSS 的多个对象的剔除效果/剪辑路径
- c# - 语法错误 - 您的 SQL 语法有错误;检查在第 1 行的 '****' 附近使用的正确语法