【问题标题】:HTML File link - force download alwaysHTML 文件链接 - 始终强制下载
【发布时间】:2018-03-14 16:20:59
【问题描述】:

我有一个显示上传文件列表的 Django 视图,用户可以单击它们开始下载。

部署项目时,我们发现浏览器打开而不是下载一个文件。它似乎与 .dxf 扩展名有关。

这是链接的创建方式:

<a href="{{ MEDIA_URL }}{{ file.url }}" target="blank">...</a>

结果:

http://localhost:8003/media/folder/whatever.dxf

那么,为什么同一个浏览器会有不同的行为呢?如果我在本地主机上运行它,那么它会下载文件。但是访问真实的服务器,它会打开它。我可以阻止服务器在浏览器中打开它们吗?

【问题讨论】:

  • 这取决于服务器配置。浏览器可以选择在浏览器中显示文件,就像通常处理 PDF 和 txt 文件一样。您要么需要设置标题以强制下载,要么为此配置网络服务器

标签: html django browser download server


【解决方案1】:

您可以尝试添加新的 Django 视图来处理下载。

urls.py

from django.conf.urls import url
import views

urlpatterns = [
    url(r'^download/$', views.DownloadView.as_view(), name='download')
]

views.py

import urllib
from django.http import HttpResponse
from django.views.generic.base import View


class DownloadView(View):
    def get(self, request):
        location = request.GET.get('location')
        file = urllib.urlretrieve(location)
        contents = open(file[0], 'r')
        content_type = '%s' % file[1].type
        response = HttpResponse(contents, content_type=content_type)
        response['Content-Disposition'] = 'attachment; filename="%s"' % location.split('/')[-1]
        return response

template.html

<a href="/download/?location={{ MEDIA_URL }}{{ file.url }}">...</a>

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 2010-11-03
    • 2014-11-12
    • 2021-08-27
    • 1970-01-01
    • 2011-09-07
    相关资源
    最近更新 更多