【问题标题】:Is there a way to provide file download without reading the file from path in Java?有没有办法在不从 Java 路径中读取文件的情况下提供文件下载?
【发布时间】: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


【解决方案1】:

您似乎正在使用 Apache POI SmartXls 创建 Excel 工作簿。查看它的 Javadoc,Workbook.write 方法似乎接受了要写入的输出流。

因此,您应该能够直接写入响应流,例如:

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();
    // do some stuff with the workbook
    workbook.write(outputStream);
    return response;
}));

【讨论】:

  • 我正在使用 SmartXLS 编写工作簿...我想知道是否有办法做到这一点,而无需将工作簿写入文件夹并将文件夹中的文件读取到请求中。 ..
  • 同样的答案仍然适用 - 我已经编辑了答案以反映这一点。您可以将 Workbook 对象直接写入响应的 OutputStream,完全绕过文件系统。
猜你喜欢
  • 2020-09-12
  • 2013-10-24
  • 2019-10-01
  • 2018-07-22
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
  • 2010-10-02
  • 1970-01-01
相关资源
最近更新 更多