skip to Main Content

In my Angular 15 project I’m storing files (PutObjectCommand) and copying files (CopyObjectCommand).

Using @aws-sdk/[email protected]

The PutObjectCommand is working fine. However, the CopyObjectCommand does not actually copy the file.

The data I’m passing to copy is:

Bucket: "simplify-pilot-media-dev"
CopySource: "/simplify-pilot-media-dev/profiles/0972000547780992.jpg"
Key: "profiles/0972000547780999.jpg"

(I also tried without the leading / before the bucket name of the copySource).

And I get a good response also:

enter image description here

However, the file is not copied in the bucket.
Btw, I really want to RENAME the file, therefore I also call the DeleteObjectCommand after copying.

Here’s my code:

async copyFile(fileSource: string, fileTarget: string, deleteSource: boolean = false ): Promise<any> {
    const bucket = environment.awsBucket;
    const s3Client = new S3Client({ 
      region: environment.awsRegion,
      //credentials: fromIni({profile: 'dev'}) });
      credentials: {        
        accessKeyId: environment.awsAccessKeyS3,
        secretAccessKey: environment.awsSecretS3,
      }
    });

    const params = {
      Bucket: bucket,
      CopySource: '/' + bucket + '/' + fileSource,      
      Key: fileTarget,
    };
    console.log('About to call AWS S3 copy file with: ', params);
    try {
      const results = await s3Client.send(new CopyObjectCommand(params));
      console.log('Copied S3 file: ', results);
      if (!results) {
        return results;
      }
      if (deleteSource) {
        const paramsDelete = {
          Bucket: bucket,                
          Key: fileSource,
        };
        const resultsDelete = await s3Client.send(new DeleteObjectCommand(params));
        console.log('Deleted S3 file: ', resultsDelete);
        return resultsDelete;
      } else {
        return results;
      }      
    } catch (err) {
      console.log('There was an error renaming your file: ', err);
        return false;
    }
  }

2

Answers


  1. Chosen as BEST ANSWER

    So, ChatGPT 4 caught my mistake immediately, and gave an explanation.

    It seems I am passing params to the delete command, instead of the paramsDelete object I prepared (copy-paste risk...).

    What happened is that I asked to delete the exact same new copy of the file I just created a second ago, instead of the old file I copied from (Yes, ChatGPT even explained this etiology...).

    Now, I'm not sure if I'm more happy to see this resolved, or more concerned with the potential risks of AI in the near future...


  2. Your CopySource is being created as:

    CopySource: '/' + bucket + '/' + fileSource,
    

    However, the documentation says that the string form is: {bucket}/{key}

    Therefore, remove the leading slash from the CopySource:

    CopySource: bucket + '/' + fileSource,      
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search