python - 无法在 Twisted 中获取上传的文件

标签 python upload twisted twisted.web

我正在尝试运行一个简单的服务,该服务将通过 HTTP POST 接受文件上传,但是在确定 post 请求完成后实际文件数据所在的位置时遇到一些问题。

到目前为止我的代码是:

from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import reactor

#import cgi

class FormPage(Resource):
    def render_GET(self, request):
        return """
<html>
<body>
<form method="POST">
    Text: <input name="text1" type="text" /><br />
    File: <input name="file1" type="file" /><br />
    <input type="submit" />
</form>
</body>
</html>
"""

    def render_POST(self, request):
        response = '<p>File: %s</p>' % request.args['file1'][0]
        response += '<p>Content: %s</p>' % request.content.read()
        return '<html><body>You submitted: %s</body></html>' % (response)

root = Resource()
root.putChild("form", FormPage())
factory = Site(root)
reactor.listenTCP(8080, factory)
reactor.run()

我得到的回应是:

You submitted:

File: test.txt

Content: text1=sdfsd&file1=test.txt

大多数everything else我可以找到有关该主题的信息,指的是使用 IRequest 据说具有 IRequest.files 的对象属性,但未在 documentation 中列出,当我运行它时它会抛出错误。

收到文件后的最终目标是将其移动到特定文件夹,然后运行一些进一步的代码。

最佳答案

我也遇到过类似的问题。事实上,您在问题下的评论中解决了这个问题,但为了澄清和总结,我正在写这个答案。

为了上传文件,您需要将表单的enctype设置为multipart/form-data,如下所示:

<form enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" name="submit" value="Submit">
</form>

现在您可以通过 request.args['file'] 访问原始文件的数据。要获取原始名称,您需要解析 request.content,即:

import re
filename = re.search(r'name="file"; filename="(.*)"', content).group(1)

我不确定这些参数(名称文件名)是否总是按照这个特定的顺序,所以要小心。另请记住,如果您有多个文件输入,它将无法工作。

关于python - 无法在 Twisted 中获取上传的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17350733/

相关文章:

python - 在 crontab 中设置路径的正确方法是什么?

python - 与 0 比较的异常

php - HTTP 与 FTP 上传

php - 间歇性问题: POST requests getting corrupted

python - 如何检查身份验证是否适用于扭曲?

python - Twisted:WAITING所有 deferred 触发

Python 使用 Django 将 python-amazon-simple-product-api 结果转换为 json

python - 使用正则表达式(在 python 中)获取数学表达式(单个字母、数字、方程...)

python - "CSRF verification failed"尝试上传文件或使用文件浏览器为 Django 创建文件夹时

python - 扭曲的框架需要一些澄清