将上传文件内容传递给WSGI

5
我正在编写一个简单的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' />

我的问题是fields(cgi.FieldStorage)只有文件名,没有文件内容。我希望上传文件时能够同时上传文件内容。
以下是fields变量的值:
"FieldStorage(None,None,[MiniFieldStorage('file','CatchSkull-large.jpg'),MiniFieldStorage('email','chamith@gmail.com'),MiniFieldStorage('operation','Upload'),MiniFieldStorage('current','upload')])"
请忽略其他字段,它们是表单上的其他字段。
谢谢您的帮助。

2
尽管您试图从头开始编写程序是非常值得称赞的,但我通常会建议使用Flask来编写WSGI应用程序。 - Markus Unterwaditzer
1个回答

6

最终我找到了答案。我忘记在HTML表单中加入enctype属性。

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

然后一切都顺利进行了。
谢谢。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接