【问题标题】:Downloading a file using Django使用 Django 下载文件
【发布时间】:2018-04-27 14:47:13
【问题描述】:

我正在尝试在 Django 中启用以前上传的文件的下载,这是我目前使用的代码:

def downloadview(request):
    path=os.path.join('media', 'files', '5560026113', '20180412231515.jpg' )
    response = HttpResponse()
    response['Content-Type']=''
    response['Content-Disposition'] = "attachment; filename='Testname'"
    response['X-Sendfile']=smart_str(os.path.join(path))
    return response

这个试验的灵感来自this thread,但我不明白它是否起作用。下载的是一个空的 txt 文件,而不是存储在服务器上的图像。 在这个试用代码中,确切的文件名和扩展名被硬编码在路径变量中。

【问题讨论】:

    标签: python django download


    【解决方案1】:

    这是一种通过 Django 提供文件的方法(虽然这通常不是一个好方法,但更好的方法是使用 nginx 等网络服务器提供文件 - 出于性能原因):

    from mimetypes import guess_type
    from django.http import HttpResponse
    
    file_path=os.path.join('media', 'files', '5560026113', '20180412231515.jpg' )
    
    with open(file_path, 'rb') as f:
        response = HttpResponse(f, content_type=guess_type(file_path)[0])
        response['Content-Length'] = len(response.content)
        return response
    

    guess_type 从文件扩展名推断 content_type。 https://docs.python.org/3/library/mimetypes.html

    更多关于 HttpResponse 的信息在这里:https://docs.djangoproject.com/en/2.0/ref/request-response/#django.http.HttpResponse

    这就是为什么不推荐通过 Django 提供文件的原因,虽然不推荐只是意味着你应该明白你在做什么: https://docs.djangoproject.com/en/2.0/howto/static-files/deployment/

    【讨论】:

    • 谢谢,有没有办法不指定内容类型?这些文件可以是不同的类型,而不仅仅是 jpg。
    • @MarcusGrass,我更新了答案,添加了内容类型的自动推断。它是可选的,但如果你不这样做,Django 只会从你的项目设置中推入默认编码(通常是文本内容类型),所以如果可能的话最好指定它,尽管大部分时间都不会破坏,因为大多数现代浏览器可以处理这些事情......但有时他们不能。
    • 很抱歉,您的回复接受晚了,这真的很糟糕。它的工作原理是打开正确的文件,但在浏览器中,自动将其下载到文件然后重定向,这可能吗? (我可以管理的重定向,只是让它下载到磁盘而不是在浏览器中显示)。
    • 没关系,我通过添加内容配置和 x-file 来修复它!
    猜你喜欢
    • 2015-10-18
    • 2020-10-26
    • 2019-01-11
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    相关资源
    最近更新 更多