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

3 投票
1 回答
1169 浏览
提问于 2025-04-17 22:18

我正在使用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."

那么我该如何处理这种数据呢?cherrypy把它转换成了一个'.Part'文件,但我想要的是原始的WAV数据。我是不是漏掉了什么头信息之类的?

更新

Jason - 你会看到我故意没有发送任何头信息,因为我想看看cherrypy会原样返回什么。这是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 个回答

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。这样做之后,我相信用同样的方法就能解决你的问题。

撰写回答