我使用cherrypy作为服务器。此服务器使您能够下载.mp3文件。我使用以下代码使.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)
答案 0 :(得分:3)
尝试将包含mp3文件的目录设置为静态目录。你的樱桃配件应该包含这样的东西:
'/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>