0

I need to copy images between OneNote pages, using a patch request. How can I do this with the MS Graph API?

Freewalker
  • 6,329
  • 4
  • 51
  • 70

1 Answers1

0

Here's the working implementation in TypeScript. The image is just embedded in the HTML (not Microsoft's documented way to insert an image but it works fine).

const resourceUrl = "https://graph.microsoft.com/v1.0/users('someone@test.com')/onenote/resources/{resourceId}/$value";
const imageData = await downloadImage(client, resourceUrl);
const b64 = Buffer.from(imageData).toString("base64");
const htmlString = `<p>test image:</p><img width="30" src="data:image/jpeg;base64,${b64}" />`;
const patchData = {
  target: "body",
  action: "prepend",
  content: htmlString,
};
await client
  .api(`/me/onenote/pages/${testInsertPageId}/content`)
  .patch([patchData]);

export async function downloadImage(
  client: Client,
  imgSrc: string,
): Promise<Uint8Array> {
  const result: ReadableStream = await client.api(imgSrc).get();
  const reader = result.getReader();

  let data: Uint8Array = new Uint8Array();
  let readResult = await reader.read();
  while (!readResult.done) {
    const value: Uint8Array = readResult.value;
    const prevData = data;
    data = new Uint8Array(data.length + value.length);
    data.set(prevData);
    data.set(value, prevData.length);

    readResult = await reader.read();
  }

  return data;
}

Freewalker
  • 6,329
  • 4
  • 51
  • 70