Download File from Bucket
Components
- Bucket Name
- Object Name (Key)
Object Name
Name of the object we want to download.
- .NET
- PHP
- Python
- Javascript
- GO
If you want to download a specific version of an object, you should use the following code.
GetObjectRequest request = new GetObjectRequest
{
BucketName = bucketName,
Key = keyName,
VersionId = "foo"
};
Resource Base
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace GetObjectExample
{
using System;
using System.IO;
using System.Threading.Tasks;
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
/// <summary>
/// This example shows how to use the Amazon Simple Storage System
/// (Amazon S3) client to copy an object from an Amazon S3 bucket to
/// another location such as your local system. The code uses the AWS
/// SDK for .NET version 3.7 and .NET Core 5.0.
/// </summary>
class GetObject
{
private const string OBJECT_NAME = "<OBJECT_NAME>";
public static async Task Main()
{
const string bucketName = "<BUCKET_NAME>";
var keyName = OBJECT_NAME;
var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("<ACCESS-KEY>", "<SECRET-KEY>");
var config = new AmazonS3Config { ServiceURL = "<ENDPOINT>" };
IAmazonS3 _s3Client = new AmazonS3Client(awsCredentials, config);
await ReadObjectDataAsync(_s3Client, bucketName, keyName);
}
/// <summary>
/// This method copies the contents of the object keyName to another
/// location, for example, to your local system.
/// </summary>
/// <param name="client">The initialize S3 client used to call
/// GetObjectAsync.</param>
/// <param name="bucketName">The name of the S3 bucket which contains
/// the object to copy.</param>
/// <param name="keyName">The name of the object you want to copy.</param>
static async Task ReadObjectDataAsync(IAmazonS3 client, string bucketName, string keyName)
{
string responseBody = string.Empty;
try
{
GetObjectRequest request = new GetObjectRequest
{
BucketName = bucketName,
Key = keyName,
};
using (GetObjectResponse response = await client.GetObjectAsync(request))
using (Stream responseStream = response.ResponseStream)
using (StreamReader reader = new StreamReader(responseStream))
{
// Assume you have "title" as medata added to the object.
string title = response.Metadata["x-amz-meta-title"];
string contentType = response.Headers["Content-Type"];
Console.WriteLine($"Object metadata, Title: {title}");
Console.WriteLine($"Content type: {contentType}");
// Retrieve the contents of the file.
responseBody = reader.ReadToEnd();
// Write the contents of the file to disk.
string filePath = keyName;
Console.WriteLine("File successfully downloaded");
}
}
catch (AmazonS3Exception e)
{
// If the bucket or the object do not exist
Console.WriteLine($"Error: '{e.Message}'");
}
}
}
}
<?php
require('client.php');
$object = $client->getObject([
'Bucket' => $config['sample_bucket'],
'Key' => 'file-uploaded-from-php-sdk.png']);
file_put_contents('../files/file-downloaded-by-php-sdk.png', $object['Body']->getContents());
If you want to download a specific version of an object, you should use the following code.
s3.download_file('mybucket, 'hello.txt', '/tmp/hello.txt', ExtraArgs={'VersionId': 'foo'})
Resource Base
import boto3
import logging
from botocore.exceptions import ClientError
logging.basicConfig(level=logging.INFO)
try:
s3_resource = boto3.resource(
's3',
endpoint_url='endpoint_url',
aws_access_key_id='access_key',
aws_secret_access_key='secret_key'
)
except Exception as exc:
logging.error(exc)
else:
try:
# bucket
bucket = s3_resource.Bucket('bucket_name')
object_name = 'object_name.txt'
download_path = '/the/abs/path/to/file.txt'
bucket.download_file(
object_name,
download_path
)
except ClientError as e:
logging.error(e)
// Import required AWS SDK clients and commands for Node.js
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3');
const fs = require('fs');
// Create an S3 client service object
const s3 = new S3Client({
region: 'default',
endpoint: 'endpoint_url',
credentials: {
accessKeyId: 'access_key',
secretAccessKey: 'secret_key',
},
});
const param = { Bucket: 'sample_bucket', Key: 'file.png' };
// call S3 to retrieve upload file to specified bucket
const run = async () => {
try {
const data = await s3.send(new GetObjectCommand(param));
const ws = fs.createWriteStream(
__dirname + '/../files/download-from-nodejs-sdk.png'
);
data.Body.pipe(ws);
console.log('Success');
} catch (err) {
console.log('Error', err);
}
};
run();
If you want to download a specific version of an object, you should use the following code.
&s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(item),
VersionId: "foo",
})
Resource Base
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"fmt"
"os"
)
// Downloads an item from an S3 Bucket in the region configured in the shared config
// or AWS_REGION environment variable.
//
// Usage:
// go run s3_download_object.go BUCKET ITEM
func main() {
if len(os.Args) != 3 {
exitErrorf("Bucket and item names required\nUsage: %s bucket_name item_name",
os.Args[0])
}
bucket := os.Args[1]
item := os.Args[2]
file, err := os.Create(item)
if err != nil {
exitErrorf("Unable to open file %q, %v", item, err)
}
defer file.Close()
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
Credentials: credentials.NewStaticCredentials("<ACCESS_KEY>", "<SECRET_KEY>", ""),
Region: aws.String("default"),
Endpoint: aws.String("<ENDPOINT_URL>"),
})
downloader := s3manager.NewDownloader(sess)
numBytes, err := downloader.Download(file,
&s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(item),
})
if err != nil {
exitErrorf("Unable to download item %q, %v", item, err)
}
fmt.Println("Downloaded", file.Name(), numBytes, "bytes")
}
func exitErrorf(msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg+"\n", args...)
os.Exit(1)
}
The following command can be used to execute the aforementioned code, presuming the code file is called s3_download_object.go:
go run s3_download_object.go BUCKET ITEM