python - 获取上传文件内容到wsgi

标签 python wsgi

我正在编写一个简单的 wsgi 脚本来上传文件。使用 html 格式。

以下是wsgi脚本,

import os
import cgi
import cgitb; cgitb.enable()


class upfile(object):

    def __init__(self):
        self.script_dir = os.path.dirname(__file__)
        self.errors = []


    def __call__(self, environ, start_response):


        f = open(os.path.join(self.script_dir, 'upload.html'))
        self.output = f.read()
        f.close()

        self.response_content_type = 'text/html;charset=UTF-8'
        fields = None
        if 'POST' == environ['REQUEST_METHOD'] :        
            fields = cgi.FieldStorage(fp=environ['wsgi.input'],environ=environ, keep_blank_values=1)
            fileitem = fields['file']
            fn = os.path.basename(fileitem.filename) 
            open('uploads/' + fn, 'wb').write(fileitem.file.read())


        self.output = self.output % {"filepath":str(fields)} # Just to see the contents

        response_headers = [('Content-type', self.response_content_type),('Content-Length', str(len(self.output)))]
        status = '200 OK'
        start_response(status, response_headers)
        return [self.output]

application = upfile()

然后在我的 HTML 表单中,我像往常一样放置一个文件字段,

<input type='file' name='file' />

我的问题是字段 (cgi.FieldStorage) 只有文件名。没有文件内容。我不仅要上传文件名,还要上传文件内容。

以下是字段变量的值,

"FieldStorage(None, None, [MiniFieldStorage('file', 'CatchSkull-large.jpg'), MiniFieldStorage('email', 'chamith@gmail.com'), MiniFieldStorage('operation', '上传'), MiniFieldStorage('当前', '上传')])"

请忽略其他字段,它们是表单上的其他字段。

提前致谢。

最佳答案

我终于找到了答案。我错过了将 enctype 放在 HTML 表单上,

<form id="upload" name="upload" method="POST" enctype="multipart/form-data">

然后一切就OK了。

谢谢。

关于python - 获取上传文件内容到wsgi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14355409/

相关文章:

python - 在 python 中搜索 wsgi 测试插件

python - 根据值在 df 中创建包含星期几和星期几的列

python - 使用上下文管理器连接到 sqlite3 数据库

python - 使用 SQLAlchemy 添加到数据库时出现奇怪的类型错误

python - 如何从 django 中的表中检索评论回复

python - Django virtualenv、pythonpath 问题

django - 确保只有一个工作人员在运行多个工作人员的 Pyramid 网络应用程序中启动 apscheduler 事件

python - Django错误: 'myproject.wsgi.application' could not be loaded

Python IDLE 不接受引号