Python接收HTML表单文件

2 投票
2 回答
2383 浏览
提问于 2025-04-17 04:30

我有一个表单,里面有一个输入框和一个提交按钮:

<input type="file" name="filename" size="25">

我还有一个Python文件来处理提交的数据:

def post(self):

在这个表单中,我上传的是一个.xml文件,在Python的处理函数里,我想把这个'foo.xml'文件传给另一个函数去验证(使用minixsv)。

我的问题是,怎么才能拿到这个文件呢?我试过:

form = cgi.FieldStorage()

inputfile = form.getvalue('filename')

但是这样做会把内容放到inputfile里,我并没有一个真正的'foo.xml'文件可以传给minisxv函数,因为它需要的是一个.xml文件,而不是文本...

更新 我找到一个可以接受文本而不是输入文件的函数,还是谢谢你们的帮助。

2 个回答

0

这可能不是最好的答案,但为什么不考虑在你的 inputfile 变量上使用 StringIO 呢?然后把这个 StringIO 对象当作文件句柄传给你的 minisxv 函数?另外,为什么不为 foo.xml 打开一个新的文件句柄,把 inputfile 的内容保存到这个文件里(也就是用 open),然后再把 foo.xml 传给你的 minisxv 函数呢?

2

有时候,我们需要从一个字符串中提取出XML内容。比如,minidom库里有一个叫做 parseString 的函数,而lxml库里有 etree.XML

如果你已经有了这些内容,可以使用 StringIO 来创建一个类似文件的对象:

from StringIO import StringIO
content = form.getvalue('filename')
fileh = StringIO(content)
# You can now call fileh.read, or iterate over it

如果你一定要在硬盘上保存一个文件,可以使用 tempfile.mkstemp

import tempfile
content = form.getvalue('filename')
tmpf, tmpfn = tempfile.mkstemp()
tmpf.write(content)
tmpf.close()
# Now, give tmpfn to the function expecting a filename

os.unlink(tmpfn) # Finally, delete the file

撰写回答