从POST数据中将WAV字节保存到磁盘(cherrypy)

时间:2014-03-14 12:55:34

标签: python post wav cherrypy

我正在使用cherrypy将WAV文件从浏览器保存到本地磁盘。传入:

{'audio_file': [<cherrypy._cpreqbody.Part object at 0x7fd95a409a90>, <cherrypy._cpreqbody.Part object at 0x7fd95a178190>], 'user_data': u'{"id":"1255733204",'audio_length': [u'10.03102', u'22.012517', u'22.012517']}

我收到此错误:

try:
        f = open('/audiostory/'+filename,'wb')
        logging.debug( '[SAVEAUDIO] tried to write all of audio_file input at once' )
        f.write(kw.get('audio_file'))
        f.close()
        logging.debug( ('saved media file %s to /audiostory/' % f.name) )
except Exception as e:
        logging.debug( ('saved media NOT saved %s because %s' % (f.name,str(e))) )

"Must be convertible to a buffer, not Part."

那么我如何处理这种数据,那就是转换为'.Part',但它应该是原始的wav数据?我错过了标题还是其他什么?

已更新

杰森 - 你会看到我故意没有发送任何标题或诸如此类的东西,因为我想知道什么樱桃会带来原始的。这是cherrypy site.py文件:

@cherrypy.expose
def saveaudio(self, *args, **kw):
    import audiosave
    return audiosave.raw_audio(kw.get('audio_file'))

和audiosave中的功能:

def raw_audio(raw):
""" is fed a raw stream of data (I think) and saves it to disk, with logging. """
import json
import logging        
LOG_FILENAME = 'error.log'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
logging.debug( '[SAVEAUDIO(raw)]'+str(raw) )
filename = assign_filename()
try:
    #SAVE FILE TO DISK /s/audiostory/
    f = open('/home/djotjog/webapps/s/audiostory/'+filename,'wb')
    logging.debug( '[SAVEAUDIO] tried to write all of audio_file input at once' )
    f.write(raw)
    f.close()
    logging.debug( ('media SAVED %s' % f.name) )
except Exception as e:
    logging.debug( ('media NOT saved %s because %s' % (f.name,str(e))) )
    return json.dumps({"result":"414","message":"ERROR: Error saving Media file "+f.name})
return raw

我也尝试了f.write(raw.file.read())但是发生了同样的错误。

1 个答案:

答案 0 :(得分:4)

这个完整的示例演示了一个CherryPy服务器,它提供HTML表单,然后接收从客户端上传的文件。

html = """
<html>
<body>
<form enctype="multipart/form-data" method="post" action="audio">
    <input type="file" name="recording">
    <button type="submit">Upload</button>
</form>
</body></html>
"""

import cherrypy

class Server:
    @cherrypy.expose
    def index(self):
        return html

    @cherrypy.expose
    def audio(self, recording):
        with open('out.dat', 'wb') as f:
            f.write(recording.file.read())

    @classmethod
    def run(cls):
        cherrypy.quickstart(cls())

Server.run()

当我提炼您的问题时,我注意到的一个关键方面是您的HTML表单未正确声明enctype。相反,它说encrypte="multipart/form-data"。我确定了'enctype'。在此之后,我希望遵循相同的技术将适合您。