我正在尝试创建文件对象的下载。该文件是使用django-filebrowser添加的,这意味着它被转换为指向该文件的字符串路径。我尝试过以下几种方法:
f = Obj.objects.get(id=obj_id)
myfile = FileObject(os.path.join(MEDIA_ROOT, f.Audio.path))
...
response = HttpResponse(myfile, content_type="audio/mpeg")
response['Content-Disposition'] = 'attachment; filename=myfile.mp3'
return response下载的文件包含文件位置的路径字符串,而不是文件。有没有人能就如何访问文件对象提供帮助?
发布于 2012-08-07 19:57:13
f = Obj.objects.get(id=obj_id)
myfile = open(os.path.join(MEDIA_ROOT, f.Audio.path)).read()
...
response = HttpResponse(myfile, content_type="audio/mpeg")
response['Content-Disposition'] = 'attachment; filename=myfile.mp3'
return response注意!这对内存不友好!因为整个文件都放入了内存中。你最好使用use服务器来提供文件服务,或者如果你想使用Django来提供文件服务,你可以使用xsendfile或者看看这个thread
发布于 2012-08-07 19:56:10
您需要打开该文件,并在响应中发送回它的二进制内容。所以就像这样:
fileObject = FileObject(os.path.join(MEDIA_ROOT, f.Audio.path))
myfile = open(fileObject.path)
response = HttpResponse(myfile.read(), mimetype="audio/mpeg")
response['Content-Disposition'] = 'attachment; filename=myfile.mp3'
return response希望这能得到你想要的。
https://stackoverflow.com/questions/11845309
复制相似问题