From 88f487bfededd0531630b4339117643d8aa93f54 Mon Sep 17 00:00:00 2001 From: Andrea Cecchi Date: Mon, 2 Sep 2024 17:24:27 +0200 Subject: [PATCH] Customize @@display-file to allow to download files with proper filename --- CHANGES.rst | 4 ++- .../plone/policy/browser/configure.zcml | 8 +++++ .../plone/policy/browser/display_file.py | 29 +++++++++++++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 src/design/plone/policy/browser/display_file.py diff --git a/CHANGES.rst b/CHANGES.rst index 6071aa9..60d67f6 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -4,7 +4,9 @@ Changelog 4.0.11 (unreleased) ------------------- -- Nothing changed yet. +- Customize @@display-file to allow to download files with proper filename. + (backport of https://github.com/RedTurtle/redturtle.volto/pull/113). + [cekk] 4.0.10 (2024-07-12) diff --git a/src/design/plone/policy/browser/configure.zcml b/src/design/plone/policy/browser/configure.zcml index 4c86ed0..7b9aee3 100644 --- a/src/design/plone/policy/browser/configure.zcml +++ b/src/design/plone/policy/browser/configure.zcml @@ -20,5 +20,13 @@ permission="zope2.View" /> + + diff --git a/src/design/plone/policy/browser/display_file.py b/src/design/plone/policy/browser/display_file.py new file mode 100644 index 0000000..f3215d2 --- /dev/null +++ b/src/design/plone/policy/browser/display_file.py @@ -0,0 +1,29 @@ +from plone.namedfile.browser import DisplayFile as BaseView +from urllib.parse import quote + + +class DisplayFile(BaseView): + """ + Custom view + """ + + def set_headers(self, file): + """ + backport of https://github.com/RedTurtle/redturtle.volto/pull/113 + + We need to add filename to the reponse because otherwise the browser + use the field name as filename (last path element). + + content-disposition should be "inline" to allow to display the file in the browser + without forcing download (with "attachment" the browser will download it). + """ + super().set_headers(file=file) + + filename = getattr(file, "filename", "") + if filename is not None: + if not isinstance(filename, str): + filename = str(filename, "utf-8", errors="ignore") + filename = quote(filename.encode("utf8")) + self.request.response.setHeader( + "Content-Disposition", f"inline; filename*=UTF-8''{filename}" + )