Преглед на файлове

Prevent encoding error in headers when download a file

Bastien Sevajol (Algoo) преди 7 години
родител
ревизия
9e0918ab50
променени са 2 файла, в които са добавени 20 реда и са изтрити 2 реда
  1. 4 2
      tracim/tracim/controllers/content.py
  2. 16 0
      tracim/tracim/lib/utils.py

+ 4 - 2
tracim/tracim/controllers/content.py Целия файл

@@ -20,7 +20,7 @@ from tracim.controllers import TIMWorkspaceContentRestController
20 20
 from tracim.lib import CST
21 21
 from tracim.lib.base import BaseController
22 22
 from tracim.lib.base import logger
23
-from tracim.lib.utils import SameValueError
23
+from tracim.lib.utils import SameValueError, get_valid_header_file_name
24 24
 from tracim.lib.content import ContentApi
25 25
 from tracim.lib.helpers import convert_id_into_instances
26 26
 from tracim.lib.predicates import current_user_is_reader
@@ -231,7 +231,9 @@ class UserWorkspaceFolderFileRestController(TIMWorkspaceContentRestController):
231 231
             tg.response.headers['Content-type'] = str(revision_to_send.file_mimetype)
232 232
 
233 233
         tg.response.headers['Content-Type'] = content_type
234
-        tg.response.headers['Content-Disposition'] = str('attachment; filename="{}"'.format(revision_to_send.file_name))
234
+        file_name = get_valid_header_file_name(revision_to_send.file_name)
235
+        tg.response.headers['Content-Disposition'] = \
236
+            str('attachment; filename="{}"'.format(file_name))
235 237
         return revision_to_send.file_content
236 238
 
237 239
 

+ 16 - 0
tracim/tracim/lib/utils.py Целия файл

@@ -123,3 +123,19 @@ class ErrorPageApplicationWrapper(BaseErrorPageApplicationWrapper):
123 123
             title=resp.title,
124 124
             comment=resp.comment,
125 125
         )
126
+
127
+
128
+def get_valid_header_file_name(file_name: str) -> str:
129
+    """
130
+    :param file_name: file name to test
131
+    :return: Return given string if compatible to header encoding, or
132
+    download.ext if not.
133
+    """
134
+    try:
135
+        file_name.encode('iso-8859-1')
136
+        return file_name
137
+    except UnicodeEncodeError:
138
+        split_file_name = file_name.split('.')
139
+        if len(split_file_name) > 1:  # If > 1 so file have extension
140
+            return 'download.{0}'.format(split_file_name[-1])
141
+        return 'download'