I want to copy a file from one folder to another on the same S3 bucket. while doing this I am getting an error NoSuchKey: The specified key does not exist my code is given below.
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
}
Error message
{
"err": "NoSuchKey: The specified key does not exist."
"status code": 404
}
CodePudding user response:
Possible reason is that url.PathEscape replaces slashes in path with /
CodePudding user response:
Use url.QueryEscape instead of url.PathEscape as url.QueryEscape can encode special characters such as which cannot be encoded by url.PathEscape (this technique worked for me).
...
_, err := svc.CopyObject(
&s3.CopyObjectInput{
Bucket: aws.String("document.as.a.service.test"),
CopySource: aws.String(url.QueryEscape(source)),
Key: aws.String(newPath),
},
)
...
And sometimes if copySource is not properly encoded error can be displayed as NoSuchKey: The specified key does not exist
Just in case to avoid confusion Go-AWS-SDK copyObject functions copySource will be the path of an existing file, and Key is the newPath or destination that you want your file to be copied.
