Skip to content

Commit

Permalink
Use Content-Disposition instead of inferring file extension from MIME…
Browse files Browse the repository at this point in the history
… type
  • Loading branch information
nas-tabchiche committed Apr 25, 2024
1 parent 733b773 commit 2139101
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 89 deletions.
3 changes: 3 additions & 0 deletions backend/core/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -1126,6 +1126,9 @@ def attachment(self, request, pk):
response = HttpResponse(
evidence.attachment,
content_type=content_type,
headers={
"Content-Disposition": f"attachment; filename={evidence.filename()}"
},
status=status.HTTP_200_OK,
)
return response
Expand Down
84 changes: 0 additions & 84 deletions frontend/src/lib/utils/mimetypes.ts

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { BASE_API_URL } from '$lib/utils/constants';

import { error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { mimeTypes } from '$lib/utils/mimetypes';

export const GET: RequestHandler = async ({ fetch, setHeaders, params }) => {
const endpoint = `${BASE_API_URL}/evidences/${params.id}/attachment`;
Expand All @@ -19,9 +18,14 @@ export const GET: RequestHandler = async ({ fetch, setHeaders, params }) => {
return new Response('No Content-Type header', { status: 400 });
}

const fileExtension = mimeTypes[contentType] ? mimeTypes[contentType][0] : 'bin';
if (!mimeTypes[contentType]) {
console.warn(`Unknown content type ${contentType}`);
const contentDisposition = attachmentResponse.headers.get('Content-Disposition');
if (!contentDisposition) {
return new Response('No Content-Disposition header', { status: 400 });
}

const fileName = contentDisposition?.split('filename=')[1];
if (!fileName) {
return new Response('No filename in Content-Disposition header', { status: 400 });
}

const reader = attachmentResponse.body.getReader();
Expand All @@ -43,7 +47,7 @@ export const GET: RequestHandler = async ({ fetch, setHeaders, params }) => {

setHeaders({
'Content-Type': contentType ?? 'application/octet-stream',
'Content-Disposition': `attachment; filename="${params.id}.${fileExtension}"`
'Content-Disposition': `attachment; filename="${fileName}"`
});
return new Response(stream, { status: attachmentResponse.status });
} catch (err) {
Expand Down

0 comments on commit 2139101

Please sign in to comment.