我正在尝试弄清楚如何使用 django 流式传输 mp3 文件。我使用了 http://djangosnippets.org/snippets/365/ 中的一些代码帮助我解决这个问题。由于某种原因,下面的代码给我的文件大小比服务器上存储的实际文件小。下载窗口中显示的大小正确,但实际文件要小得多。我尝试使用下面的代码发送文本文件,它似乎工作得很好。我似乎无法弄清楚出了什么问题。
def play_song(request, id):
song = Song.objects.get(pk=id)
# song is an object which has a FileField name file
filepath = os.path.join(MP3_STORAGE, song.file.name).replace('\\', '/')
wrapper = FileWrapper(file(filepath))
response = HttpResponse(wrapper, content_type='audio/mpeg')
response['Content-Length'] = os.path.getsize(filepath.replace('/', '\\'))
response['Content-Disposition'] = 'attachment; filename=%s' % song.file.name
return response
最佳答案
你读过http://djangosnippets.org/snippets/365/上的评论了吗? ?尝试:
For people on Windows you'll need to specify "read binary" mode for anything other than a text file:
wrapper = FileWrapper(file(filename), "rb")
或
Got this working with a few tweaks:
wrapper = FileWrapper(open(filename, 'rb'))
关于python - 使用 django 进行 mp3 流传输的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9417911/