How to upload file to s3 bucket with django rest framework api

Viewed 1809

I am trying to upload a file to AWS bucket in Django project

@api_view(['POST'])
def upload_image(request):
        image = request.FILES['image']
        file_name = request.POST.get('file_name')

    access_key = settings.AWS_ACCESS_KEY_ID
    access_secret_key = settings.AWS_SECRET_ACCESS_KEY
    bucket_name = settings.AWS_STORAGE_BUCKET_NAME 
# bucket_name value is "https://s3.region.amazonaws.com/bucket_name/sub_bucket_name/" 
# I am not sure if it is correct way to give bucket name where I want my file to be uploaded

    
    client_s3 = boto3.client(
        's3',
        aws_access_key_id = access_key,
        aws_secret_access_key= access_secret_key
    )

    client_s3.upload_file(
          file_name,
          bucket_name,
          image
    )

    url = f'{end_point}{bucket_name}/{file_name}'

    return Response({'success': True,
                     'message': "File has been uploaded",
                     'url': url
                     },
                    status=status.HTTP_200_OK)

and this is how I am passing the file and file name to the api through the postman. enter image description here The error that I am getting is - "FileNotFoundError: [Errno 2] No such file or directory: "name of file""

I have read the tutorial, It looked fairly simple to upload the file to s3 bucket with boto3. but, some how I am not able to upload the file.

1 Answers

If this is your bucket url:

https://s3.region.amazonaws.com/bucket_name/sub_bucket_name/

then

file_name = 'yourlocalfile.jpg'
bucket = 'bucket_name'
key = 'sub_bucket_name/myfile.jpg'

client_s3.upload_file(file_name, key, ExtraArgs={'ContentType': 'image/jpeg'})
Related