从 S3 Golang 复制对象时出错 "NoSuchKey: The specified key does not exist"

Error while copying object from S3 Golang "NoSuchKey: The specified key does not exist"

我想将文件从一个文件夹复制到同一个 S3 存储桶上的另一个文件夹。执行此操作时出现错误 NoSuchKey: The specified key does not exist 下面给出了我的代码。

sess, err := session.NewSession(&aws.Config{Region: aws.String("ap-south-1")})
if err != nil {
    return nil, err
}
Oldpath := "folder1/folder2/a+b.pdf"
newBaseFolder  := "folder3"
svc := s3.New(sess)
bucketName := "mybucket.test"
source := bucketName + "/" + oldPath                                 // Oldpath = "folder1/folder2/a+b.pdf"
                                                                     //newBaseFolder = "folder3"
newPath := newBaseFolder + "/" + strings.SplitN(oldPath, "/", 2)[1] //newPath = "folder3/folder2/a+b.pdf" 
_, err = svc.CopyObject(&s3.CopyObjectInput{
            Bucket:     aws.String(bucketName), // bucketName = "mybucket.test" 
            CopySource: aws.String(url.PathEscape(source)),
            Key:        aws.String(newPath)})
if err != nil {
        return nil, err
    }

错误信息

{
"err": "NoSuchKey: The specified key does not exist."
"status code": 404
}

可能的原因是 url.PathEscape 将路径中的斜杠替换为 %2F

使用 url.QueryEscape 而不是 url.PathEscape 因为 url.QueryEscape 可以编码特殊字符,例如 +url.PathEscape 无法编码(此技术适用于我)。

...
_, err := svc.CopyObject(
            &s3.CopyObjectInput{
                Bucket:     aws.String("document.as.a.service.test"),
                CopySource: aws.String(url.QueryEscape(source)),
                Key: aws.String(newPath),
            },
        )
...

有时如果 copySource 编码不正确,错误会显示为 NoSuchKey: The specified key does not exist

以防混淆 Go-AWS-SDK copyObject 函数 copySource 将是 现有文件的路径 ,并且 Key 是您希望复制文件的新路径或目的地