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 (Content Management API | Contentful) 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.”

Did you get help? Seems a similar problem we have.

Same question. Did either of you figure this out?

I had a same problem, and found that we can replace asset files with the Upload API.

https://www.contentful.com/developers/docs/references/content-management-api/#associating-an-upload-with-an-asset

const asset = (await environment.getAssets()).items[0];

const upload = await environment.createUpload({
  file: fs.createReadStream('new-image.jpg'),
});

asset.fields.file.ja = {
  contentType: "image/jpeg",
  fileName: 'new-image.jpg',
  uploadFrom: {
    sys: {
      type: "Link",
      linkType: "Upload",
      id: upload.sys.id, 
    },
  },
};

await asset.update();
await asset.processForAllLocales();
1 Like