Skip to main content
 首页 » 编程设计

python之cgi.FieldStorage 类如何处理文件上传

2025年05月04日10qlqwjy

整个问题几乎都在标题中。

我能在类里面找到的唯一文档是非常 sparing cgi documentation并且丝毫没有提及该类如何接收文件、如何存储文件、支持哪些功能等。

我对上传文件的存储位置很感兴趣。显然它不在内存中,因为 Bottle提到 FileStorage.read() 函数对大文件很危险。如果它放在磁盘上,我想将它移动到一个永久位置,而不必在 Python 中读取它,将它一点一点地复制到一个新位置。

但是由于该类的文档很差,我不知道从哪里开始。有什么想法吗?

请您参考如下方法:

有点晚了,但我自己正在调查:

这一切都归结为 cgi.py 中的“make_file”方法:

def make_file(self, binary=None): 
    import tempfile 
    return tempfile.TemporaryFile("w+b") 

临时文件文档 ( http://docs.python.org/2/library/tempfile.html ) 指出该文件是在从平台相关列表中选择的默认目录中创建的,但用户可以通过设置环境变量之一来控制目录位置:TMPDIR、TEMP 或TMP。

另请注意文档:

Under Unix, the directory entry for the file is removed immediately after the file is created. Other platforms do not support this; your code should not rely on a temporary file created using this function having or not having a visible name in the file system.

希望这对您有所帮助。