Create new file in a folder with Apps Script using Google Advanced Drive service

Maybe this is a bit late, but by looking at the REST API docs, it shows that you can use Drive.Files.insert to insert into any folder. You simply have to add the folder's ID in the properties of the file you are inserting as such:

var file = {
   title: 'myFile',
   "parents": [{'id':folder.getId()}],  //<--By setting this parent ID to the folder's ID, it creates this file in the correct folder.
   mimeType: 'image/png'
 };

Folder ID can be obtained from the shareable link using the Google Drive GUI or as shown here. (e.g. Use the Execute function on the right.)

Alternatively, you can access the folder by name by replacing the folder.getID() with Drive.getFoldersByName('name of folder').

This is helpful because Drive.Files.insert() accepts arguments while Drive.createFile() and Drive.createFolder() do not.


The easiest way to create a new file is to use DriveApp which comes with pure Google Apps Script:

var dir = DriveApp.getFolderById("{dir_id}");
var file = dir.createFile(name, content);

If you do not know exact directory's id you can get the folder by its name:

var dir = DriveApp.getFoldersByName(name).next();

The next() is there because getFoldersByName() returns collection of all directories whose names match given value.

Also check DriveApp docs: https://developers.google.com/apps-script/reference/drive/drive-app