0

Currently i am able to add multiple images into kentico. but how can I add images into specific folder using Kentico API. I am using Kentico/Kontent-management Package in Node.js project.

Maulik Patel
  • 717
  • 1
  • 10
  • 22

1 Answers1

1

I would retrieve folders and select the one you want (desiredFolder) and then when creating asset I would set the id (or extenal_id if set) to specify to what folder to upload the asset under.

JS SDK should wrap the capabilities of the Kontent REST Management API v2, in this case, the crucial is folder property of the Asset model

const folders = await mClient.listAssetFolders()
  .toPromise(); // get folders
const desiredFolder = folders.items.find(folder => folder.name = "Your delsired folder"); // select desired folder
const assetData = await getAssetDataDataFromUrl(article.image.url)
  .toPromise(); // load binary how you want it
const assetObject = await mClient.uploadBinaryFile().withData(assetData).toPromise(); // upload binary

const asset = await mClient.addAsset()
  .withData({
    descriptions: [{
      language: {
        codename: argv.language
      },
      description: `Image for article ${article.title}`
    }],
    external_id: article.image.id,
    file_reference: {
      ...assetObject.data
    },
    folder:  {
      id: desiredFolder.id,
      // external_id: desiredFolder.externalId // also possible to use external ID
    }
  })
  .toPromise();

If you already have the assets in Kontent, you could just update assets to specific folder:

const updatedAsset = await mClient.upsertAsset().withData({
  // not sure if you need to add whole asset object like: `...asset`, but i think it is not necessary
  folder:  {
    id: desiredFolder.id,
    // external_id: desiredFolder.externalId // also possible to use external ID
  }
}).toPromise()

My workflow when creating scripts like that (i.e. this one) is to take a look to repo tests in this case these two: list folders and add assets. Most of the IDEs (VS Code in my case) should load type definitions and help you with model structure via intellisence.

Simply007
  • 444
  • 3
  • 14
  • I have also added the info to my journal to make it more searchable: https://ondrej.chrastina.tech/journal/specify-folder-when-uploading-asset-via-kontent-js-management-sdk – Simply007 Jul 31 '20 at 12:33