Reputation: 125
I am sending an excel file as a request in postman and need to upload this to s3 . I access the file from request and send it to s3.
@api_view(['POST'])
def excel_upload(request):
print("request", request)
excel_file = request.FILES['file']
print("excel_file", excel_file) // this prints the name of the excel file i am sending in request
upload_to_aws(excel_file,'X1excelsheets','s3_file_name')
and here is the function to upload file to s3.
def upload_to_aws(local_file, bucket, s3_file):
s3 = boto3.client('s3', aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY)
try:
s3.upload_file(local_file, bucket, s3_file)
print("Upload Successful")
return True
except FileNotFoundError:
print("The file was not found")
return False
except NoCredentialsError:
print("Credentials not available")
return False
uploaded = upload_to_aws('local_file', 'bucket_name', 's3_file_name')
I am trying to use this particular post
https://medium.com/bilesanmiahmad/how-to-upload-a-file-to-amazon-s3-in-python-68757a1867c6
to get things done . Error:ValueError: Filename must be a string
Upvotes: 3
Views: 10311
Reputation: 2678
Save execel_file locally received from request.POST.get('file_name')
in '/tmp' directory or according where your backend code will deploy, because upload_file takes path as string.
@api_view(['POST'])
def excel_upload(request):
excel_file = request.FILES['file']
file_name = request.POST.get('file_name')
with open('/tmp'+file_name, 'wb+') as destination:
for chunk in excel_file.chunks():
destination.write(chunk)
upload_to_aws('/tmp' + file_name,'X1excelsheets','s3_file_name')
Update upload_to_aws as following.
client_s3.upload_file('/tmp/name.png', bucket, file_name, ExtraArgs={'ContentType': 'image/png'})
Upvotes: 0
Reputation: 174
I made my configuration with AWSCLI
S3_BUCKET_NAME = 'YOUR_BUCKET'
s3 = boto3.client('s3')
with open(file, 'rb') as f:
s3.upload_fileobj(f, S3_BUCKET_NAME, file)
I have been getting the same error so I just used upload_fileobj instead of upload_file. This worked fine for me, you can try it.
Upvotes: 6