python - 值错误: Filename must be a string while uploading file to s3 bucket

标签 python django amazon-s3 boto3

我正在 postman 中发送一个 excel 文件作为请求,并且需要将其上传到 s3 。 我通过请求访问该文件并将其发送到 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')

这里是上传文件到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')

我正在尝试使用这个特定的帖子

https://medium.com/bilesanmiahmad/how-to-upload-a-file-to-amazon-s3-in-python-68757a1867c6

把事情做好。 错误:ValueError:文件名必须是字符串

最佳答案

我用 AWSCLI 进行了配置

S3_BUCKET_NAME = 'YOUR_BUCKET'

s3 = boto3.client('s3')
with open(file, 'rb') as f:
    s3.upload_fileobj(f, S3_BUCKET_NAME, file)

我遇到了同样的错误,所以我只是使用 upload_fileobj 而不是 upload_file。这对我来说效果很好,你可以尝试一下。

关于python - 值错误: Filename must be a string while uploading file to s3 bucket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59891320/

相关文章:

python - Django REST Framework 需要哈希密码才能登录

python - DRF获取OneToOne模型的所有字段

带 SSL 的 WordPress

amazon-web-services - 用于在 S3 事件上触发 Lambda 的 Cloudformation 模板

python - 调试生成器和迭代器

Python:os.mkdir 的代码在哪里?

python - 获取 groupby 和 nlargest 之后的行索引

python - 我如何在 Django 中定义 3 个以上模型之间的多对多关系?

django - PostgreSQL 日期格式

amazon-web-services - 如何使用 CICD 在 Elastic Beanstalk 环境上实现蓝绿部署