file.getDownloadUrl() not working for Google Add-on Apps Script

Viewed 431

I am creating a google add-on for Google Drive. I am using the DriveApp class to access and handle files. I would like to be able to generate a link for downloading a file. Eventually, I want to send this download link to a server for further file processing.

DriveApp's file class appears to have a perfect method for this purpose, file.getDownloadUrl(), which "Gets the URL that can be used to download the file."

Unfortunately, I am seeing some strange behavior and I am not sure if I am using the method correctly.

First, the method returns null when called on Google's filetypes, e.g. application/vnd.google-apps.documentor application/vnd.google-apps.spreadsheet. It makes sense that we may need to set some kind of parameter for what filetype we'd like to export to, but that does not appear to be an option for getDownloadUrl().

Second, when getDownloadUrl() does return a url, access to the url is severely restricted. Unless I am on Chrome and signed into the file owner's G Suite account, I cannot access the file. Signing into the owner account, but browsing on Firefox also returns a 403 error.

I have a flask server running on a set of Drive API credentials. Is there a way to authorize those credentials to access this download link?

Any help would be greatly appreciated!

1 Answers

Files that have the Google MIME type cannot be downloaded directly, and file.getDownloadUrl() returns null.

For example, a Spreadsheet.

Before downloading manually, you can see that the file is converted to .xlsx. So to download it, you need to convert the file into something.


    // --- Apps Script ---
    let new_file = Drive.Files.insert({ //DriveApi
        title: file.getName(), //name
        parents: [{
          id: file.getParents().next().getId() //folder
        }],
        mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" //new mimeType
      },
      file.getBlob()
    );

    console.log(new_file.getDownloadUrl())

However, to download a file from this link, you need to be logged in to Google and have access to the file in Drive.

Otherwise, you can get a blob of a file and convert it to a file in another place, for example, on your server.


    // --- Apps Script ---
    let blob = file.getBlob()
    let blob_type = blob.getContentType() // for some reason, this is a application/pdf, so it will download as .pdf
    let blob_string = blob.getDataAsString() // data of this blob as a String with UTF-8 encoding


    // --- JS ---
    // convert to js blob
    let js_blob = new Blob([blob_string], {
      type: blob_type
    });
    // and download
    let a = document.createElement("a")
    document.body.appendChild(a)
    a.style = "display: none"
    let url = window.URL.createObjectURL(js_blob)
    a.href = url
    a.download = "fileName.pdf" //file name and extension
    a.click()
    a.remove()
    window.URL.revokeObjectURL(url)

Related