让Django将响应作为“不同的文件名”返回 [英] Make Django return response as a "different filename"

查看:142
本文介绍了让Django将响应作为“不同的文件名”返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django视图,它返回一个带有特殊MIME类型的 HttpResponse ,以使用户的浏览器下载该文件,而不是在浏览器中查看它。问题是响应将被保存的默认文件名是用户试图访问的URL。

I have a Django view which returns an HttpResponse with a special MIME type to make the user's browser "download" the file instead of view it in the browser. The problem is that the default filename that the response will be saved as is the URL which the user tried to access.

有没有办法在其中包含默认文件名 HttpResponse 对象还是我必须重定向到另一个URL才能实现这一目标?

Is there any way to include a default filename in the HttpResponse object or do I have to redirect to a different URL to make this happen?

推荐答案

docs 中有一个相关示例:

from django.http import HttpResponse

def some_view(request):
    # Create the HttpResponse object with the appropriate headers.
    response = HttpResponse(mimetype='application/pdf', <snip>)
    response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
    return response

这篇关于让Django将响应作为“不同的文件名”返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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