Django下载链接仅在新标签中工作
这让我发疯,我正在开发一个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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论