我正在尝试使用FileResponse.set_header()将Content-Disposition设置为attachment,以便可以在我的 python/django 支持的网站中下载音频文件而不是在浏览器上播放。有什么办法可以实现下面的代码以使其工作?
song = models.song.objects.filter(id__exact=song_id).first()
file_name = ntpath.basename(song.songfile.url)
content_type = 'audio/mpeg'
with open(identify_song.songfile.path, 'rb') as my_f:
file_like = my_f
response = FileResponse(my_f, content_type=content_type, as_attachment=True, filename="{}".format(file_name))
response['Content-Disposition'] = 'attachment; filename="{}"'.format(file_name)
size = response['Content-Length'] = os.path.getsize(identify_song.songfile.path)
#print(file_name)
return(response)
这段代码没有给我任何错误,但它不起作用。
所以我FileResponse.set_header()在 django 文档中发现了,所以我尝试像这样使用它。
`song = models.song.objects.filter(id__exact=song_id).first()
file_name = ntpath.basename(song.songfile.url)
FileResponse.set_headers(file_name, filelike='audio/mpeg', as_attachment=True)`
然后我得到一个错误AttributeError:'str'对象没有属性'filename'。请任何人都可以帮助我,或者如果在 django 中有另一种方法可以做到这一点,我将非常感谢某人的帮助。或者我可以在 django、Nginx 或 Javascript 中设置我的Content-Disposition的任何其他可能方式。
