下载文件显示在 tomcat bin 文件夹中

Download file showing in tomcat bin folder

当我 运行 我的 war 文件在 Tomcat 服务器上时,我 运行 我在 chrome 上的项目并从我的项目下载 xls 文件,然后此文件显示在 tomcat bin 文件夹以及我们计算机的下载文件夹中。

请建议我如何停止 tomcat bin 文件夹中的此下载文件

谢谢

String FILE_EXTENSION = ".xlsx";
            DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
            filename = "SearchPayment_Transactions_" + df.format(new Date()) + FILE_EXTENSION;
            File file = new File(filename);

            // this Writes the workbook
            FileOutputStream out = new FileOutputStream(file);
            wb.write(out);
            out.flush();
            out.close();
            wb.dispose();
            fileInputStream = new FileInputStream(file);
            addActionMessage(filename + " written successfully on disk.");

我认为这个问题可以解决,只需修复你想要创建文件的位置

字符串FILE_EXTENSION = ".xlsx"; DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss"); 文件名 = "SearchPayment_Transactions_" + df.format(new Date()) + FILE_EXTENSION; File file = new File(path any fixed directory like temp\filename);

只要您指定要生成文件的路径,那么它只会在该目录中生成。请对生成文件的路径给予适当的权限,这将解决您的问题。

该文件在您的计算机上出现两次,因为您的 servlet 代码在将 *.xlsx 文件发送到您的浏览器之前将其保存到磁盘。这是您在代码中选择的行为。

但是请注意,您代码中的 file 相对 路径,因此您编写的文件夹是工作目录(根据 OS) 你的服务器。工作目录的值未在 Servlet 规范中定义,并且可能因系统而异。

更好的解决方案是:

  • 要么根本不写任何文件,直接把你的数据写到ServletResponse#getOutputStream(),
  • 或者将文件写入Servlet的临时目录,可以通过(File) servletContext.getAttribute(ServletContext.TEMPDIR)获取。例如。您可以将 file 变量替换为:
final File file = new File((File) servletContext.getAttribute(ServletContext.TEMPDIR), filename);