Skip to content

Commit

Permalink
Fix mimetype determination for empty files (#3661)
Browse files Browse the repository at this point in the history
Closes #3658
  • Loading branch information
jmsmkn authored Oct 28, 2024
1 parent 792b809 commit cda0704
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
22 changes: 16 additions & 6 deletions app/grandchallenge/uploads/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,12 +201,22 @@ def assign_permissions(self):
def mimetype_from_file(self):
if self.status != self.StatusChoices.COMPLETED:
raise RuntimeError("Cannot get mimetype of incomplete upload")
header = self._client.get_object(
Bucket=self.bucket,
Key=self.key,
# 2048 bytes for best results with libmagic
Range="bytes=0-2047",
)["Body"].read()

response = self._client.head_object(Bucket=self.bucket, Key=self.key)
object_size = int(response["ContentLength"])

# 2048 bytes for best results with libmagic
max_bytes = min(2047, object_size)

if max_bytes == 0:
return "application/x-empty"
else:
header = self._client.get_object(
Bucket=self.bucket,
Key=self.key,
Range=f"bytes=0-{max_bytes}",
)["Body"].read()

return magic.from_buffer(header, mime=True)

def create_multipart_upload(self):
Expand Down
1 change: 1 addition & 0 deletions app/tests/uploads_tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,7 @@ def test_can_upload_more_other_objects(settings):
@pytest.mark.parametrize(
"content,expected_mimetype",
(
(b"", "application/x-empty"),
(b"hello", "text/plain"),
(
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x00\x00\x00\x00:~\x9bU\x00\x00\x00\nIDATx\x9cc`\x00\x00\x00\x02\x00\x01H\xaf\xa4q\x00\x00\x00\x00IEND\xaeB`\x82",
Expand Down

0 comments on commit cda0704

Please sign in to comment.