gpt4 book ai didi

python - 无法在 django 中提供 mp3 文件

转载 作者:行者123 更新时间:2023-12-01 05:57:11 24 4
gpt4 key购买 nike

我正在尝试将 MP3 文件提供给可在音频标签中使用的 django 模板。我正在使用以下 View 。

def get_file(request):
filename = FILE_PATH + '\\' + files['k']
wrapper = FileWrapper(file(filename))
response = HttpResponse(wrapper, content_type='audio/mp3')
response['Content-Length'] = os.path.getsize(filename)
return response

但是我无法获取该文件,当我访问与该 View 相对应的 URL 时,它仅提供一个零 kb MP3 文件。

最佳答案

您需要以二进制模式打开 MP3 文件:

wrapper = FileWrapper(open(filename, 'rb'))

如果您以文本模式(默认)打开文件,则各种行结尾都会标准化为 \n,这对于文本来说非常有用,但对于 MP3 文件等二进制信息来说,这是一个大问题.

请注意,我使用 open function在这里,不是file constructor ;来自 file 文档:

When opening a file, it’s preferable to use open() instead of invoking this constructor directly. file is more suited to type testing (for example, writing isinstance(f, file)).

关于python - 无法在 django 中提供 mp3 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11896454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com