google-apps-scriptgoogle-drive-apiurlfetch

i have tried downloading an image using google appscript but the response.getAs() or any other functions always returns 4 bytes as Blob. why?


i have tried downloading an image using google appscript but the response.getAs() or any other functions always returns 4 bytes as Blob.

In google form i am trying to add an imageitem using appscript from internet and download it to avoid further URLFetch calls.

While showing from the disk (for offline file loaded from Google Drive) it works absolutely fine. However when loading from the internet for the first time it is failing.

Exception: Could not add image, please wait a minute and try again.

File blob is just 4 bytes all the time

Can someone pitch in to help.

folder - destination folder in google drive to save file fileName - fileName of the downloaded image fileURL - public url of the image

function downloadImage(folder, fileName, fileURL) {
  var response = UrlFetchApp.fetch(fileURL);
  if(response.getResponseCode() == 200){
    var fileBlob = response.getAs("image/jpeg");
    var file = folder.createFile(fileName+".jpeg",fileBlob,MimeType.JPEG);
    return file;
    debugger;  // Stop to observe if in debugger
  }else{
    Logger.log("Whats this now???");
  }
}

Size of the file is 400 KB, but it is not working for any image i have tried downloading.


Solution

  • You are using the method createFile(name, content, mimeType) and passing Blob as content, hence the 4 bytes size. The content should be of type string for this method.

    You want to use the createFile(blob) method, and to the returned file, assign a name.

    Example:

    function downloadImage(folder, fileName, fileURL) {
      var response = UrlFetchApp.fetch(fileURL);
      if(response.getResponseCode() == 200){
        var fileBlob = response.getAs("image/jpeg");
        var file = folder.createFile(fileBlob);
        file.setName(fileName);
        return file;
      }else{
        console.log(response.getAllHeaders())
      }
    }