用B下载S3文件

2024-03-29 07:17:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试建立一个应用程序,用户可以在其中下载存储在S3存储桶中的文件。我可以设置我的bucket并获得正确的文件,但它不会下载,这给了我一个错误:No such file or directory: 'media/user_1/imageName.jpg'知道为什么吗?这似乎是一个相对容易的问题,但我似乎不太明白。我可以正确地删除一个图像,因此它能够识别正确的图像。

这是我的观点

def download(request, project_id=None):
    conn = S3Connection('AWS_BUCKET_KEY', 'AWS_SECRET_KEY')
    b = Bucket(conn, 'BUCKET_NAME')
    k = Key(b)
    instance = get_object_or_404(Project, id=project_id)
    k.key = 'media/'+str(instance.image)
    k.get_contents_to_filename(str(k.key))
    return redirect("/dashboard/")

Tags: or文件instancekey图像projectawsid
2条回答

问题是您正在下载到一个不存在的本地目录(media/user1)。你需要:

  • 先在本地计算机上创建目录
  • 只需使用文件名而不是完整路径
  • 使用完整路径,但用另一个字符替换斜杠(/),这将确保文件名的唯一性,而不必创建目录

最后一个选择可以通过:

k.get_contents_to_filename(str(k.key).replace('/', '_'))

另请参见:Boto3 to download all files from a S3 Bucket

使用boto3下载文件非常简单,在使用此代码之前,请在系统级别配置您的AWS凭据。

client = boto3.client('s3')

// if your bucket name is mybucket and the file path is test/abc.txt
// then the Bucket='mybucket' Prefix='test'

resp = client.list_objects_v2(Bucket="<your bucket name>", Prefix="<prefix of the s3 folder>") 

for obj in resp['Contents']:
    key = obj['Key']
    //to read s3 file contents as String
    response = client.get_object(Bucket="<your bucket name>",
                         Key=key)
    print(response['Body'].read().decode('utf-8'))

    //to download the file to local
    client.download_file('<your bucket name>', key, key.replace('test',''))

replace是用s3文件名在本地定位文件,如果不替换,它将尝试另存为“test/abc.txt”。

相关问题 更多 >