diff --git a/django/core/files/uploadedfile.py b/django/core/files/uploadedfile.py index 60c354a9f7..3ba7f995c6 100644 --- a/django/core/files/uploadedfile.py +++ b/django/core/files/uploadedfile.py @@ -58,7 +58,8 @@ class TemporaryUploadedFile(UploadedFile): A file uploaded to a temporary location (i.e. stream-to-disk). """ def __init__(self, name, content_type, size, charset, content_type_extra=None): - file = tempfile.NamedTemporaryFile(suffix='.upload', dir=settings.FILE_UPLOAD_TEMP_DIR) + _, ext = os.path.splitext(name) + file = tempfile.NamedTemporaryFile(suffix='.upload' + ext, dir=settings.FILE_UPLOAD_TEMP_DIR) super().__init__(file, name, content_type, size, charset, content_type_extra) def temporary_file_path(self): diff --git a/tests/files/tests.py b/tests/files/tests.py index 5e165a998f..a414a81ad3 100644 --- a/tests/files/tests.py +++ b/tests/files/tests.py @@ -12,7 +12,8 @@ from django.core.files.base import ContentFile from django.core.files.move import file_move_safe from django.core.files.temp import NamedTemporaryFile from django.core.files.uploadedfile import ( - InMemoryUploadedFile, SimpleUploadedFile, UploadedFile, + InMemoryUploadedFile, SimpleUploadedFile, TemporaryUploadedFile, + UploadedFile, ) try: @@ -214,6 +215,13 @@ class InMemoryUploadedFileTests(unittest.TestCase): self.assertEqual(f.read(), '1') +class TemporaryUploadedFileTests(unittest.TestCase): + def test_extension_kept(self): + """The temporary file name has the same suffix as the original file.""" + with TemporaryUploadedFile('test.txt', 'text/plain', 1, 'utf8') as temp_file: + self.assertTrue(temp_file.file.name.endswith('.upload.txt')) + + class DimensionClosingBug(unittest.TestCase): """ get_image_dimensions() properly closes files (#8817)