编程语言
首页 > 编程语言> > python-将WAV字节从POST数据保存到磁盘(cherrypy)

python-将WAV字节从POST数据保存到磁盘(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数据?我是否缺少标题或其他内容?

更新

杰森(Jason)-您会看到我故意没有发送任何标头或其他信息,因为我想看看小巧的东西会带来原始效果.这是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()),但发生相同的错误.

解决方法:

这个完整的示例演示了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.在那之后,我希望遵循同样的技术对您有用.

标签:post,wav,cherrypy,python
来源: https://codeday.me/bug/20191029/1962528.html