Django下载链接仅在新标签中工作

发布于 2025-01-26 10:44:24 字数 828 浏览 2 评论 0原文

这让我发疯,我正在开发一个Django应用程序,需要提供指向位于媒体文件夹中的文件的下载链接。如果我在空白选项卡中键入URL,则可以下载文件,但是如果我单击网站的链接,则不会发生任何事情。我意识到这可能是因为文件的URL与网站的起源不同,并且据我了解,浏览器不允许下载,这是正确的吗?有什么办法吗?

url of the website (in development): http://localhost:8000/django_app/view_name
url of the file: http://localhost:8000/django_app/media/file.ext

我已经尝试了以下HTML HREF:

href="../media/file.ext" download target="_blank"

以及以下视图:

def download_file(request):


fl_path = settings.MEDIA_ROOT + "\\filename.ext"
filename = "file_name"

mime_type, _ = mimetypes.guess_type(fl_path)
response = HttpResponse(fl, content_type=mime_type)
response['Content-Disposition'] = "attachment; filename=%s" % filename

return response

当我单击链接时,没有发生任何错误。如果我在新标签中打开链接,它将正常下载文件...请注意,我需要能够动态更改HREF链接。 谢谢!

This is driving me crazy, I'm developing a django app and need to provide a download link to a file located in the media folder. If I type the url in a blank tab it works fine, the file is downloaded, but if I click on the link from the website nothing happens. I realize this might be because the url to the file doesn't have the same origin that the website and from what I understood the browser won't allow the download, is this correct? Is there any way around?

url of the website (in development): http://localhost:8000/django_app/view_name
url of the file: http://localhost:8000/django_app/media/file.ext

I've tried the following html href:

href="../media/file.ext" download target="_blank"

And the following view:

def download_file(request):


fl_path = settings.MEDIA_ROOT + "\\filename.ext"
filename = "file_name"

mime_type, _ = mimetypes.guess_type(fl_path)
response = HttpResponse(fl, content_type=mime_type)
response['Content-Disposition'] = "attachment; filename=%s" % filename

return response

Nothing happens when I click on the link, no error generated. If I open the link in a new tab it downloads the file normally... Note that I need to be able to change the href link dynamically.
Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文