无法在django中提供mp3文件 [英] Not able to serve mp3 files in django

查看:140
本文介绍了无法在django中提供mp3文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to serve MP3 files to django templates which can be used in audio tag. I am using the following 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

但我不能获取文件,而我访问该视图对应的URL,它只是提供零kb的MP3文件。

But I am not able to get the file , while I visit the URL corresponding to the view its just serves a zero kb MP3 file.

推荐答案

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

You'll need to open the MP3 file in binary mode:

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

如果您以textmode(默认)打开文件,则各种行结束标准化为 \\\
,这对于文本是非常好的,但是二进制信息,如MP3文件是一个大问题。

If you open the file in textmode (the default) then various line endings are normalized to \n, which is great for text, but in binary information such as an MP3 file that's a big problem.

请注意,使用 打开功能这里,而不是 文件构造函数;从文件文档:

Note that I use the open function here, not the file constructor; from the file documentation:


打开文件时,最好使用 open()而不是直接调用此构造函数。 文件更适合于键入测试(例如,写入 isinstance(f,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)).

这篇关于无法在django中提供mp3文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆