IBM / ibm-cos-sdk-js

ibm-cos-sdk-js
Apache License 2.0
38 stars 19 forks source link

How to rename the files using IBM-COS-SDK-JS #58

Closed thirukumaran-murugan closed 4 years ago

thirukumaran-murugan commented 4 years ago

I am trying to rename the files in the CLoud storage through programmatically. How it is possible to achieve it. Could you share the sample code or method name to achieve the use case?

kellerbr-ibm commented 4 years ago

Hey, sorry for the delay.

Objects can't directly be renamed, but the same result can be done by copying an object to a new name and then deleting the original one.

Here's an example for how to do it, starting with an object copytest-first-(timestamp) and renaming it to copytest-new-(timestamp):

const COS = require('ibm-cos-sdk');
const util = require('util');

const bucketName = 'testbucket';
const cos = new COS.S3({
    endpoint: 's3.us-east.cloud-object-storage.appdomain.cloud',
    apiKeyId: 'secret',
    serviceInstanceId: 'secret',
});

async function run() {
    try {
        const now = Date.now();
        const initialObjectName = 'copytest-first-' + now;
        const newObjectName = 'copytest-new-' + now;

        // Upload our object before renaming it
        await cos.putObject({
            Bucket: bucketName,
            Key: initialObjectName,
            Body: 'foo'
        }).promise();

        // Create a copy of the object with the new name
        await cos.copyObject({
            Bucket: bucketName,
            Key: newObjectName,
            CopySource: bucketName + '/' + initialObjectName
        }).promise();

        // Delete the old object
        await cos.deleteObject({
            Bucket: bucketName,
            Key: initialObjectName
        }).promise();

        // Check that the rename worked
        const results = await cos.listObjects({
            Bucket: bucketName,
            Prefix: 'copytest-'
        }).promise();

        console.log(JSON.stringify(results.Contents, null, 2));
    } catch (err) {
        console.log('Error: ' + util.inspect(err));
    }
}

run();

Running this should return something like

> node misc/examples/rename_object.es6
[
  {
    "Key": "copytest-new-1580311155880",
    "LastModified": "2020-01-29T15:19:17.040Z",
    "ETag": "\"acbd18db4cc2f85cedef654fccc4a4d8\"",
    "Size": 3,
    "StorageClass": "STANDARD",
    "Owner": {
      "DisplayName": "c883a086-431d-4fc6-bda9-3b039111e10e",
      "ID": "c883a086-431d-4fc6-bda9-3b039111e10e"
    }
  }
]

with the new object name.

thirukumaran-murugan commented 4 years ago

Hi @kellerbr-ibm , That's cool, I have achieved it through put and get object methods. Is there any official support for .Net core platform.

kellerbr-ibm commented 4 years ago

Unfortunately, we don't yet officially support the .NET ecosystem. We have it on our roadmap and hope to get to it soon.