9

我进行了搜索和搜索,但似乎找不到以任何合理方式将文件上传到我的 twisted.web 应用程序的方法。

目前,将文件上传发布到资源会产生一个request.args['file']变量,即填充了文件内容的列表。我找不到获取有关文件的任何信息的方法:mime 类型、文件名、文件大小(不只是获取字符串的长度args['file'][])等。

我读过twisted.web2 更擅长文件上传。但是我不知道它有多好,或者我将如何使用twisted.web2 来处理twisted.web 应用程序中的文件上传。

有什么建议么?这让我发疯了——哦,我查看了请求标头,并没有真正发现任何重要的东西。如何使用 Twisted 获取有关文件上传的更多元信息?

还,

我怎样才能从请求对象中获取裸露的 HTTP 请求?是否可以?

4

2 回答 2

5

这是一个老问题,但是快速搜索 stackoverflow 并没有找到类似的问题/答案,所以这里有一个twisted.web2用于文件上传的快速示例。

隐藏的表单变量file_foo与文件上传变量共享相同的名称,以显示 Twisted 将如何拆分它们:

<form action="/upload?a=1&b=2&b=3" enctype="multipart/form-data"
        method="post">
    <input type="hidden" name="foo" value="bar">
    <input type="hidden" name="file_foo" value="not a file">
    file_foo: <input type="file" name="file_foo"><br/>
    file_foo: <input type="file" name="file_foo"><br/>
    file_bar: <input type="file" name="file_bar"><br/>
    <input type="submit" value="submit">
</form>

在您的Resource.render()方法中,您可以通过以下方式访问表单变量:

def render(self, ctx):
    request = iweb.IRequest(ctx)
    for key, vals in request.args.iteritems():
        for val in vals:
            print key, val

    print 'file uploads ----------------'
    for key, records in request.files.iteritems():
        print key
        for record in records:
            name, mime, stream = record
            data = stream.read()
            print '   %s %s %s %r' % (name, mime, stream, data)

    return http.Response(stream='upload complete.')

输出:

         a: 1
         b: 2 3
       foo: bar
  file_foo: not a file

file_bar
   bar.txt MimeType('text', 'plain', {}) <open file '<fdopen>', mode 'w+b' at 0x2158a50> 'bar data.\n\n'
file_foo
   foo.txt MimeType('text', 'plain', {}) <open file '<fdopen>', mode 'w+b' at 0x2158930> 'foo data.\n\n'
   foo.txt MimeType('text', 'plain', {}) <open file '<fdopen>', mode 'w+b' at 0x21589c0> 'foo data.\n\n'
于 2011-04-27T12:39:53.267 回答
3

I did it like it is described here: solution for upload. The solution uses cgi.FieldStorage to parse the payload.

Also: For the purpose of parsing you need request.content not request[args]. As you can see, the results are almost the same as in web2 request.files.

于 2012-03-21T18:53:50.117 回答