【问题标题】:python receive file from html formpython从html表单接收文件
【发布时间】:2011-10-17 22:19:52
【问题描述】:

我有一个带有输入标签和提交按钮的表单:

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

我有一个处理帖子的 python 文件:

def post(self):

我在表单中收到的文件是一个 .xml 文件,在 python post 函数中,我想将该“foo.xml”发送到另一个要验证它的函数(使用 minixsv)

我的问题是如何检索文件?我试过了:

form = cgi.FieldStorage()

inputfile = form.getvalue('filename')

但这会将内容放在输入文件中,我本身没有“foo.xml”文件,我可以将其传递给请求 .xml 文件而不是文本的 minisxv 函数...

更新我找到了一个接受文本而不是输入文件的函数,无论如何谢谢

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    通常,还有一个函数可以从字符串中提取 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
    

    【讨论】:

      【解决方案2】:

      这可能不是最佳答案,但为什么不考虑在您的 inputfile 变量上使用 StringIO,并将 StringIO 对象作为文件句柄传递给您的 minisxv 函数呢?或者,为什么不为foo.xml 打开一个实际的新文件句柄,将输入文件的内容保存到它(即通过open),然后将foo.xml 传递给你的minisxv 函数?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-11-21
        • 2020-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多