Search code examples
curlfile-iogoogle-drive-apiapplescriptextendscript

Curl failing on Google Drive form image download


Pardon me, I'm not well-versed with curl, but I am trying to download a Google Drive image using it. The file downloads as an HTML, rather than as a jpg. I am calling the curl via Applescript shell script wrapped in an Extendscript app.doScript command, but I tried also from the Terminal and received the same file. I followed these instructions: https://stackoverflow.com/a/48133140/1810714

Here is the full Extendscript code I am working with.

var assetFolderPath = Folder.selectDialog();
var fileName = "/test.jpg";
var front = "https://drive.google.com/uc?export=download&id=";
var root = "google-drive-id#"; //the real id is here instead
var exporturl = front + root;
var ff = File(assetFolderPath + fileName);
var curlCommand = "\"curl -L -o '" + ff.fsName + "' " + "'" + exporturl + "'";
var asCode = 'do shell script ' + curlCommand + '"';
app.doScript(asCode, ScriptLanguage.APPLESCRIPT_LANGUAGE);

Thanks in advance.


Solution

  • How to download a file with the Drive API with curl

    You seem to be trying to download a file with the files.export endpoint, however in the docs it says:

    Exports a Google Doc to the requested MIME type and returns the exported content.

    That is, the export endpoint only works for Google Doc types, i.e. Sheets, Docs, Slides, etc.

    For all other types of file, what you need to use is files.get with an ?alt=media at the end of the URL. For this you need the file ID and your oauth access token.

    The curl command in bash would look something like this:

    curl \
      "https://www.googleapis.com/drive/v3/files/${FILE_ID}?alt=media" \
      --header "Authorization: Bearer ${ACCESS_TOKEN}" \
      --header 'Accept: application/json' \
      --compressed -o $OUTPUT_PATH
    

    Replace the ${} variables with the file id, the oauth access token, and the output path.

    For instance:

    curl \
      "https://www.googleapis.com/drive/v3/files/xxxxxxx?alt=media" \
      --header "Authorization: Bearer xxxxxxx" \
      --header 'Accept: application/json' \
      --compressed -o image.jpg
    

    Assuming the ID that is chosen is a .jpg file, then in the folder where this is run, it will create a image.jpg image file.

    You can find more info in the guide.

    Reference