浏览代码

Prevent encoding error in headers when download a file

Bastien Sevajol (Algoo) 8 年前
父节点
当前提交
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
 from tracim.lib import CST
20
 from tracim.lib import CST
21
 from tracim.lib.base import BaseController
21
 from tracim.lib.base import BaseController
22
 from tracim.lib.base import logger
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
 from tracim.lib.content import ContentApi
24
 from tracim.lib.content import ContentApi
25
 from tracim.lib.helpers import convert_id_into_instances
25
 from tracim.lib.helpers import convert_id_into_instances
26
 from tracim.lib.predicates import current_user_is_reader
26
 from tracim.lib.predicates import current_user_is_reader
231
             tg.response.headers['Content-type'] = str(revision_to_send.file_mimetype)
231
             tg.response.headers['Content-type'] = str(revision_to_send.file_mimetype)
232
 
232
 
233
         tg.response.headers['Content-Type'] = content_type
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
         return revision_to_send.file_content
237
         return revision_to_send.file_content
236
 
238
 
237
 
239
 

+ 16 - 0
tracim/tracim/lib/utils.py 查看文件

123
             title=resp.title,
123
             title=resp.title,
124
             comment=resp.comment,
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'