一个简单的wsgi文件上传

文件上传测试页代码:

#!c:/Python27/python 
        output= '<html><head>' +
        '<br>' + 
        '</head><body>' + 
        '<form name="form1" action=“/dynamic/postuploadfile.py” enctype="multipart/form-data" method=“post”>' +
        'File: <input type="file" name="test" size=50><br />' +
        '<input type=“submit” value="upload"/>' +
        '</form></body></html>'
def application(environ, start_response):  
    status='200 OK'   
    response_headers=[('Content-type', 'text/html'),  
                     ('Content-Length', str(len(output)))]  
    start_response(status, response_headers)  
    return [output]

 

上面

File: <input type="file" name="test" size=50>

这行中name一定不能少,否则,服务器端始终读不到文件的内容,至于为什么我一直没有找到答案,如果有路过的高手,请指点一下。

这两天就因为这个导致我,读取的内容只是数据开始分隔附,如:

-----------------------------20812054002634687841594064928

这个分隔符用来表明数据的开始,开始的时候也有一个同样的。

 

 

提交后处理代码:

import os

def upload(environ):  
       
    try: # Windows needs stdio set for binary mode.  
        import msvcrt  
        msvcrt.setmode (0, os.O_BINARY) # stdin  = 0  
        msvcrt.setmode (1, os.O_BINARY) # stdout = 1  
    except ImportError:  
        pass  
  
    # A nested FieldStorage instance holds the file  
    #fileitem = req.form['file']  
    data = environ['wsgi.input'].read(int(environ.get('CONTENT_LENGTH','0'))) 
  
    message = ''   
    open( 'c:/uploaded', 'wb').write(data)  
    message = 'The file was uploaded successfully'  

    
    return ( '<html><body>' + message + '</body><html>' )

def application(environ, start_response):  
    status='200 OK'  
    output=upload( environ )
    response_headers=[('Content-type', 'text/html'),  
                     ('Content-Length', str(len(output)))]  
    start_response(status, response_headers)  
    return [output] 

其实收到文件有点问题,除了文件本身的内容外,头和尾部还多了额外的信息,这个让我很头疼,希望路过能指点一二。
 

版权所有,禁止转载. 如需转载,请先征得博主的同意,并且表明文章出处,否则按侵权处理.

    分享到:

One Reply to “一个简单的wsgi文件上传”

留言给rrleon 取消

你的邮箱是保密的 必填的信息用*表示