How do I create a file in a folder?
As of 2015, you should use the DriveApp service to manage files in Google Drive. DriveApp has a Folder class that allows you to create a file directly in a folder.
function createFilesInFolder() {
//This creates the folder
var folder = DriveApp.createFolder('My Folder');
//This creates a file in the folder
var file = folder.createFile('My File.txt',
'Lorem ipsum',
MimeType.PLAIN_TEXT);
}
The DocsList no longer works and has been replaced by the DriveAPI , Google App Services and Advanced Google services .
Here I leave my test code , this code creates folders - subfolders - google files - pdf - and stores them in folders and subfolders in various ways, and I hope will be helpful
function Drive_2015() { //busca un folder, si no lo hay lo crea y crea 2 sub carpetas un google document copiado en cada una de ellas
var name='folder de prueba';
var carpeta = DriveApp.getRootFolder().searchFolders("title contains '"+name+"'");
if (carpeta.hasNext()===true) {
while (carpeta.hasNext()) {
var folder = carpeta.next();
Logger.log(folder.getName()+' '+folder.getId());
}
}else{
var folder=DriveApp.getRootFolder().createFolder(name);
var parent=DriveApp.getFolderById(folder.getId()); // get parent folder
var folder2 =parent.createFolder('Subfolder'); // 1° way to create sub folder
var folder3=folder.createFolder(name+1);// 2° way to create sub folder (and more easy)
var doc = DocumentApp.create('Documento sta');
var sheet = SpreadsheetApp.create('Spreadsheet sta');
Utilities.sleep(300); // este retardo es para garantizar en el user-side la creacion del nuevo archivo
var files = DriveApp.getFilesByName('Documento sta');// or Id var file = DriveApp.getFileById(doc.getId());
while (files.hasNext()) {
var file = files.next();
Logger.log('ojo '+file.getName());
file.makeCopy(folder3);
file.makeCopy(folder2);
var file2=file.makeCopy(folder);
file2.setName('Acta individual del alumno')
var blob = file2.getAs('application/pdf');
var file2pdf = folder.createFile(blob);
var file2pdf = DriveApp.getFileById(file2pdf.getId());
var file2pdf=file2pdf.makeCopy(folder);
Logger.log('se creó: '+file.getName()+' en la carpeta: '+folder.getName()+' el PDF es: '+file2pdf.getId());
DriveApp.getFileById(file2pdf.getId()).setTrashed(true)
DriveApp.getFileById(docid).setTrashed(true)
}
}
}
Just tested the following code
function Test() {
DocsList.createFolder('Folder1').createFolder('Subfolder1').createFile('File1', 'Empty');
}
It works as expected, i.e. created a new File1
document in newly created folder My Drive\Folder1\Subfolder1
.
I just wanted to comment (but don't have the 50 reputation points).
The reason the answer above works when the original post didn't is that .createFolder applies to both DocsList.createFolder (which creates the folder in the root directory) and to Folder.createFolder which creates a sub-folder in the current folder.
It may be obvious to everyone but me - but it took me a good while to realise :-)