Home > Back-end >  Downloading .png image results in corrupted file
Downloading .png image results in corrupted file

Time:12-19

I try to download an image with FetchUrl but it results in an 4kb corrupted file. I try to download this file: Parameter Link with redirects

I was thinking it had something to do with the fact that it's a redirection link, but UrlFetch follows redirects by default. I tried the direct (server cached) link and the same corrupted file is generated, this is the direct link: https://pub-cdn.apitemplate.io/2022/12/212ebbf4-8051-446b-bc3a-1a225b2a3758.png

This is the code:

function download() {
  let imageBlob = UrlFetchApp.fetch("https://pub-cdn.apitemplate.io/2022/12/212ebbf4-8051-446b-bc3a-1a225b2a3758.png").getBlob();
  DriveApp.getFolderById("1vb7ZzdhBfsK6t154Z2CR-RpBNEKvyPB6").createFile("menu.png", imageBlob, MimeType.PNG)
}

What am I doing wrong? Thanks for any help.

CodePudding user response:

imageBlob is a blob but not a content.

createFile(blob) should be used instead of createFile(name, content, mimeType).

function download() {
  let imageBlob = UrlFetchApp.fetch("https://pub-cdn.apitemplate.io/2022/12/212ebbf4-8051-446b-bc3a-1a225b2a3758.png").getBlob();
  const file = DriveApp.getFolderById("1vb7ZzdhBfsK6t154Z2CR-RpBNEKvyPB6").createFile(imageBlob);
  file.setName("menu.png");
}
  • Related