【发布时间】:2021-04-10 09:40:52
【问题描述】:
在我的程序中,我有一个 getRequest (JavaSpark),它为我提供了一个用 Java 创建的 Excel 文件以供下载。
为此,我创建了 Excel 文件,将其保存在文件夹中,然后通过路径读取文件。
工作。
代码 - ExcelCreation:
public void createPlanWorkbook() throws Exception {
...
...
do something with workbook...
workBook.write("C:\\Users\\Develope\\Desktop\\Excel.xlsm");
}
代码 - 请求:
get("/excelfile", ((request, response) -> {
response.header("Content-disposition", "attachment; filename=Excel.xlsm;");
File file = new File("C:\\Users\\Develope\\Desktop\\Excel.xlsm");
OutputStream outputStream = response.raw().getOutputStream();
outputStream.write(Files.readAllBytes(file.toPath()));
outputStream.flush();
return response;
}));
我想知道是否有另一种方法来实现这一点。保存然后读取文件的步骤是否必要?或者有没有办法将文件直接从Javaobject放入请求中。
例如:
outputStream.write(ExcelCreaterObject().getWorkbook());
【问题讨论】:
-
您能详细说明您要做什么吗?在您的代码示例中,您没有在文件系统上创建或保存任何文件 - 您只是打开它以供阅读。然后将其所有字节读入内存,并将这些字节写入响应输出流。
-
是的,改了...
标签: java file outputstream