【问题标题】:How to download a file uploaded using django-filebrowser?如何下载使用 django-filebrowser 上传的文件?
【发布时间】:2012-08-07 11:48:27
【问题描述】:

我正在尝试创建文件对象的下载。该文件是使用 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

下载的文件包含文件位置的路径字符串,而不是文件。任何人都可以就如何访问文件对象提供帮助吗?

【问题讨论】:

标签: python django django-filebrowser


【解决方案1】:
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

注意!这对内存不友好!由于整个文件被放入内存。您最好使用网络服务器进行文件服务,或者如果您想使用 Django 进行文件服务,您可以使用xsendfile 或查看thread

【讨论】:

    【解决方案2】:

    您需要打开文件并将其二进制内容发送回响应中。所以像:

    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
    

    希望得到你想要的。

    【讨论】:

    • FileObject 来自 django-filebrowser ´from filebrowser.base import FileObject´
    • 感谢@ejey,我更新了我的示例以希望符合您需要做的事情。另外,William 的回应是值得考虑的,如果这是一个大文件,它会占用大量内存空间。
    • 我刚刚测试过,马上就遇到了问题。如果失败,我会尝试使用 chunks() 我会看看 Willian 的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 2017-03-16
    相关资源
    最近更新 更多