Skip to main content
 首页 » 编程设计

python之Cherrypy:如何从上传的文件中获取原始数据

2025年05月04日8zhengyun_ustc

我在使用 cherrypy 3.2.4 上传文件时遇到问题。 ( python 2.7) 我无法获取上传文件的原始数据。我试图调试以找到如何从响应中获取数据值但没有成功。有人知道如何解决这个问题吗?

彼得

这是我使用的代码:

    def index(self): 
    return """ 
    <html><body> 
        <h2>Upload a file</h2> 
        <form action="upload" method="post" enctype="multipart/form-data"> 
        filename: <input type="file" name="myFile" /><br /> 
        <input type="submit" /> 
        </form> 
        <h2>Download a file</h2> 
        <a href='download'>This one</a> 
    </body></html> 
    """ 
index.exposed = True 
 
def upload(self, myFile): 
    out = """<html> 
    <body> 
        myFile length: %s<br /> 
        myFile filename: %s<br /> 
        myFile mime-type: %s 
    </body> 
    </html>""" 
 
 
    cherrypy.log('-'*60) 
    cherrypy.log('0: ' + str(dir(myFile))) 
    cherrypy.log('-'*60) 
    cherrypy.log('2: ' + str(dir(cherrypy.request.headers))) 
    cherrypy.log('-'*60) 
    cherrypy.log('4: ' + str(dir(cherrypy.request.rfile))) 
    cherrypy.log('-'*60) 
    cherrypy.log('6: ' + str(cherrypy.request.rfile.readline)) 
    cherrypy.log('-'*60) 
    cherrypy.log('8: ' + str(cherrypy.request.rfile.read())) 
    cherrypy.log('-'*60) 
    cherrypy.log('-'*60) 
    cherrypy.log('-'*60) 
    # Although this just counts the file length, it demonstrates 
    # how to read large files in chunks instead of all at once. 
    # CherryPy reads the uploaded file into a temporary file; 
    # myFile.file.read reads from that. 
    size = 0 
    while True: 
        data = myFile.file.read(8192) 
        if not data: 
            break 
        size += len(data) 
    #cherrypy.log('myFile: %s' % str(dir(myFile))) 
    #cherrypy.log('File: %s' % str(myFile.read_into_file)) 
    #myFile.read_into_file('a.txt') 
    return out % (size, myFile.filename, myFile.content_type) 
upload.exposed = True 

这是输出:

[27/Jul/2014:13:38:32]  0: ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__module__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'attempt_charsets', 'boundary', 'charset', 'content_type', 'default_content_type', 'default_proc', 'file', 'filename', 'fp', 'from_fp', 'fullvalue', 'headers', 'length', 'make_file', 'maxrambytes', 'name', 'next', 'params', 'part_class', 'parts', 'process', 'processors', 'read', 'read_headers', 'read_into_file', 'read_lines_to_boundary', 'readline', 'readlines', 'type', 'value'] 
[27/Jul/2014:13:38:32]  2: ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__','__weakref__', 'clear', 'copy', 'elements', 'encode', 'encode_header_items', 'encodings', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'output', 'pop', 'popitem', 'protocol', 'setdefault', 'update', 'use_rfc_2047', 'values', 'viewitems', 'viewkeys', 'viewvalues'] 
[27/Jul/2014:13:38:32]  4: ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__module__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'close', 'read', 'readline', 'readlines', 'remaining', 'rfile'] 
[27/Jul/2014:13:38:32]  6: <bound method KnownLengthRFile.readline of <cherrypy.wsgiserver.wsgiserver2.KnownLengthRFile object at 0x0000000002FF8D30>> 
[27/Jul/2014:13:38:32]  8: 
[27/Jul/2014:13:38:32] "POST /upload HTTP/1.1" 200 172 "http://localhost:8080/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0" 

已编辑:

我尝试并找到了简单的解决方案:

def upload(self, myFile): 
    lcHDRS = {} 
    for key, val in cherrypy.request.headers.iteritems(): 
        lcHDRS[key.lower()] = val 
 
    incomingBytes = int(lcHDRS['content-length']) 
    content = myFile.file.read(incomingBytes) 
    file = open ('./upload/' + file.filename,"wb") 
    file.write(content) 
    file.close()                 
 
    return 'File was uploaded...' 

请您参考如下方法:

首先删除您的 cherrypy 日志语句。其中第 6 行是错误的。还将这些行添加到您的 while 循环中...

size = 0 
 
# NEW LINE 
all_data = bytearray() 
 
while True: 
    data = myFile.file.read(8192) 
 
    # NEW LINE 
    all_data += data 
 
    if not data: 
        break 
    size += len(data) 
 
    # to save the file use this 
 
    saved_file=open(myFile.filename, 'wb')  
    saved_file.write(all_data)  
    saved_file.close() 
 
return out % (size, myFile.filename, myFile.content_type) 

现在您只能获得前 8192 个字节。

希望这对您有所帮助!