0

I am trying to upload a picture file response into an excel as a full image not a URL from a form. The form provides me with a downloadable jpg, jpeg or png (if using a file converter) URL. I want to try to take the jpg, jpeg or png file (jpg being the best mode) and have it upload in full picture form from the URL provided. I have my code that I made in office scripts and I am getting a failed to fetch error. I also tried using non-downloadable png links from google and still got the same error.

async function main(workbook: ExcelScript.Workbook) {

const link = "https://api.typeform.com/responses/files/39ce7d7b9326c7d5f5d9366326d7254ed68fca9be7b02cca7d2550d537037809/f0439ebd2f58_20210706_083619__2___1_.png";
const response = await fetch(link);

const data = await response.arrayBuffer();
const image = convertToBase64(data);
workbook.getActiveWorksheet().addImage(image)
}

function convertToBase64(input: ArrayBuffer){
const uInt8Array = new Uint8Array(input);
const count = uInt8Array.length;

const charCodeArray = new Array(count)

for(let i - count; i >= 0; i--){
charCodeArray[i] = String.fromCharCode(uInt8Array[i]);
}

const base64 = btoa(charCodeArray.join(''));
return base64;
}

I believe this code is restricted to png files only which is a hassle since the files must be converted from jpeg or jpg to png on a third-party website. If there is also a way in the code to upload jpg or jpeg that would be much appreciated!

Thank you!

spec
  • 1
  • 1

1 Answers1

0

Can you try run the script again and open the browser developer tools (F12 for Chrome or Microsoft Edge) and see if there is some error message in the Console output saying the request has been blocked by CORS policy? If yes, you may need to either:

  • Enable CORS for that web resource on the host server side (if you own or have control over the server)
  • Or use some sort of "fetch proxy" to workaround it. Please refer to my answer to another similar question here: https://stackoverflow.com/a/66959919/6656547

BTW, I believe the Worksheet.addImage API supports both PNG and JPG images:

base64ImageString string

A base64-encoded string representing an image in either JPEG or PNG format.

Yutao Huang
  • 1,503
  • 1
  • 13
  • 25