将上传文件内容发送到wsgi

时间:2013-01-16 09:47:16

标签: 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', 'Upload'), MiniFieldStorage('current', 'upload')])"

请忽略其他字段,即表单上的其他字段。

提前致谢。

1 个答案:

答案 0 :(得分:6)

最后我想出了答案。我错过了将enctype放在HTML表单上,

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

然后所有的事情都没了。

感谢。