Pankaj Savaliya
Pankaj Savaliya

Reputation: 141

How to Update file name in FileField after file is uploaded on s3 via presigned post URL in Django?

I have integrated django-storages in Django Project. for large file sizes, I have used a pre-signed URL to upload files from externally without taking a load on my server.

by pre-signed URL, Files uploaded successfully in the s3 bucket AWS, after uploading the file in s3 I need to update the name of the file in FileField.

Upvotes: 0

Views: 291

Answers (1)

Panos Angelopoulos
Panos Angelopoulos

Reputation: 609

Probably you need something like, using the boto3 library to retrieve the file from S3 and os library to rename the file.


import boto3
import os

s3 = boto3.client('s3')

uploaded_file = s3.get_object(Bucket='your-bucket-name', Key='object-key')

new_filename = 'new_file_name.txt'
os.rename(uploaded_file['Body'].name, new_filename)

...

with open(new_filename, 'rb') as f:
    file_obj = File(f, name=new_filename)

    my_model.file_field_name = file_obj
    my_model.save()

Upvotes: 0

Related Questions