2016-09-19 54 views
0

我可以成功地列出S3 Bucket中的所有文件(jpg照片)並製作一個[] s3.Objects。現在我想從這些照片中找到指向文件的指針,但我仍然無法下載它們。從Golang上的AWS託管的圖像中獲取*文件

package main 

import (
    "fmt" 
    "log" 
    "github.com/aws/aws-sdk-go/aws/credentials" 
    "os" 
    "github.com/aws/aws-sdk-go/aws/session" 
    "github.com/aws/aws-sdk-go/aws" 
    "github.com/aws/aws-sdk-go/service/s3" 
    //"github.com/aws/aws-sdk-go/service/s3/s3manager" 
    "github.com/aws/aws-sdk-go/service/s3/s3manager" 
) 

func main() { 
    acess := "***********" 
    secret := "******" 
    log.Println(acess + secret) 
    creds := credentials.NewStaticCredentials(acess, secret, "") 
    _, err := creds.Get() 

    if err != nil { 
     fmt.Println(err) 
     os.Exit(1) 
    } 

    sess := s3.New(session.New(), &aws.Config{ 
     Credentials: creds, 
     Region: aws.String("sa-east-1"), 
     //LogLevel: aws.LogLevel(aws.LogDebug), 
    }) 

    params := &s3.ListObjectsInput{ 
     Bucket: aws.String("cescocats"), 
    } 
    // 

    resp, err := sess.ListObjects(params) 
    if err != nil { 
     fmt.Println(err) 
     os.Exit(1) 
    } 

    var allPhotos []s3.Object 

    //log.Println(resp.String()) 
    for _, key := range resp.Contents { 
     allPhotos = append(allPhotos, *key) 
    } 

    log.Println(allPhotos) 
    // Set up a new s3manager client 

    manager := s3manager.NewDownloader(session.New(), func(d *s3manager.Downloader) { 
     d.PartSize = 1 * 1024 * 1024 // 64MB per part 
    }) 
    log.Println(manager) 
    buff := new([]byte) 


    hehe := s3.GetObjectInput{Key:allPhotos[0].Key} 
    manager.Download(aws.WriteAtBuffer{}, hehe) 

} 

如何使用github.com/aws/aws-sdk-go從S3下載文件?有沒有其他方法?我真的需要下載文件才能獲取它的內容嗎?

+1

不要忽略錯誤。你忽略'svc.ListObjects(params)' – jcbwlkr

+0

謝謝@jcbwlkr。我已經知道了。 http://docs.aws.amazon.com/general/latest/gr/rande.html 我現在可以列出這些文件,但還沒有能夠下載它們 – CESCO

回答

1

嘗試這樣:

log.Printf("Fetching s3://%v/%v", bucket, key) 

buff := &aws.WriteAtBuffer{} 
s3dl := s3manager.NewDownloader(sess) 
_, err := s3dl.Download(buff, &s3.GetObjectInput{ 
    Bucket: aws.String(bucket), 
    Key: aws.String(key), 
}) 

if err != nil { 
    log.Printf("Could not download from S3: %v", err) 
} 

然後你就可以得到內容buff.Bytes()

相關問題