简体   繁体   中英

How can I add asset/Image to specific folder using Kentico

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.

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM