如何删除 CGI 正在显示的临时文件(图像)?

发布于 2024-07-17 09:34:30 字数 215 浏览 6 评论 0原文

我编写了一个 python CGI 脚本,它将文件转换为 .jpg 并将它们显示在一个简单的 HTML 页面中。 我不想用这些 .jpg 文件弄乱文件夹,因此我使用 tempfile.NamedTemporaryFile 创建一个文件来存储转换后的 .jpg 输出。 一切都很好,但我想在页面显示后删除此文件。 目前我已经设置了delete=False,但我似乎无法在不导致img 链接损坏的情况下删除该文件。

I've written a python CGI script that converts files into .jpgs and displays them in a simple HTML page. I don't want to clutter up the folders with these .jpg files, so I used tempfile.NamedTemporaryFile to create a file to store the converted .jpg output. Everything works great, but i want to remove this file after the page is displayed. Currently I have delete=False set, but i can't seem to remove the file without causing a broken img link.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

万劫不复 2024-07-24 09:34:30

您无法从 cgi 脚本中删除该文件。 因为只有在脚本运行完毕后,html 页面才会发送给用户。 然后用户浏览器解析html并获取jpg文件。

最简单的选择是将临时文件写入子目录并定期清理该目录(仅在最后几分钟存在于其中)。 有一些方法可以改进这个过程,但它们可能毫无意义。

更高级的选项(这也可能毫无意义,具体取决于您的场景)是配置 Web 服务器以根据“get jpg”请求运行脚本。 然后您可以通过脚本流式传输 jpg。 这样你就会知道 jpg 何时被获取。 并且在这个脚本中你可以异步调用一个下标来删除jpg文件。

You can't remove the file from your cgi script. Because the html page is send to the user only after your script finishes to run. And then the users browser parse the html and fetch the jpg file.

The simplest option is to write the temporary files to a sub directory and periodically clean that directory (living in it the last few minutes only). There are ways to improve this process but they are probably pointless.

A more advanced option (which is also probably pointless, depending on your scenario) is to configure the web server to run a script on the "get jpg" request. And then you can stream the jpg through your script. That way you will know when the jpg was fetched. And in this script you can call a subscript asynchronically to delete the jpg file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文