3

I am using

storages.backends.s3boto3.S3Boto3Storage

storage backend to upload files in my django project.

field declaration in model:

document = models.FileField(upload_to=s3_directory_path.user_directory_path)

user_directory_path

def user_directory_path(instance, filename):
    # TODO: Try to include this along with check filetype on the request object
    document = instance.document
    mime = magic.from_buffer(document.read(), mime=True)
    extension = mimetypes.guess_extension(mime, strict=False)
    file_name = str(uuid.uuid4()) + extension
    document.seek(0)
    return os.path.join("users", str(instance.user.id), file_name)

The saving of the document works perfectly fine, but the link which is generated force downloads the file. How can i avoid that?

ankit
  • 1,499
  • 5
  • 29
  • 46

1 Answers1

1

Have a look at this answer to a general question about forcing file downloads via HTTP response headers. See also the MDN docs about Content-Disposition.

Can you show us the response headers you get when visiting the document URL? It would be interesting to see how S3 delivers your files.

If you cannot change the headers in S3, you have the option to write a Django view that proxies the file download. Alternatively, configure your webserver (i.e. NGINX) to act as a proxy and set the required headers).

For Django, this section of the docs will show you how to set the headers.

response = HttpResponse(
    document, 
    headers={
        'Content-Type': mimetype,
        'Content-Disposition': f'attachment; filename="{document.name}"',
    }
)
jnns
  • 5,148
  • 4
  • 47
  • 74