Contentful logo

Contentful Community

Update asset file contents programatically

I want to do the following steps performed using the UI, but with code.

  1. Visit an asset (image) already uploaded.
  2. Delete the image linked to the asset
  3. Upload a new image

In other words: I need to replace the file contents of an already uploaded asset. The documentation regarding updating assets (https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets/asset/create-update-an-asset/console/js) doesn’t help me out with this case.

I tried updating the file using this code:

const image = await env.getAssets({ limit: 1, 'fields.file.fileName': fileName });
image.items[0].fields.file['en-GB'].file = fs.readFileSync(newImagePath);
image.items[0].update();

And I get this error:

“details”: “The property “file” is not allowed here.”