通过cherrypy提供mp3文件

1 投票
1 回答
1224 浏览
提问于 2025-04-16 07:37

我正在使用cherrypy作为服务器。这个服务器可以让你下载.mp3文件。我用以下代码来实现下载.mp3文件的功能。但是,下载后得到的文件是一个数据文件,而不是应该是的mp3文件。

import glob
import os.path
import cherrypy
from cherrypy.lib.static import serve_file

class Root:
    def index(self, directory="."):

        html = """<html><body><h2>Here are the files in the selected directory:</h2>
        <a href="index?directory=%s">Up</a><br />
        """ % os.path.dirname(os.path.abspath(directory))
        for filename in glob.glob(directory + '/*'):
            absPath = os.path.abspath(filename)
            if os.path.isdir(absPath):
                html += '<a href="/index?directory=' + absPath + '">' + os.path.basename(filename) + "</a> <br />"
            else:
                html += '<a href="/download/?filepath=' + absPath + '">' + os.path.basename(filename) + "</a> <br />"

        html += """</body></html>"""
        return html
    index.exposed = True

class Download:

    def index(self, filepath):
        return serve_file(filepath, "audio/mpeg", "attachment")
    index.exposed = True

if __name__ == '__main__':
    root = Root()
    root.download = Download()
    cherrypy.quickstart(root)

1 个回答

3

试着把存放mp3文件的文件夹设置为静态目录。你的cherrypy配置文件应该包含类似下面的内容:

    '/directory_with_mp3s': {
        'tools.staticdir.on': True, 
        'tools.staticdir.dir': 'directory_with_mp3s'
}

这样你就可以不需要Download这个类了,只需在html中创建指向mp3文件的链接,格式可以是这样的:

<a href="directory_with_mp3s/somemp3.mp3">some mp3</a>

撰写回答