1

I am creating Text files with a Google script I found from here

They save by default in my Google Drive.

I want to save them in a specific called folder called TextFiles in my Google drive

create text files with

function dlFile(str) {
  let file = DriveApp.getRootFolder().createFile('Hi.txt', str);

  // Create little HTML popup with the URL of the download
  let htmlTemplate = HtmlService.createTemplateFromFile('download.html');
  htmlTemplate.dataFromServerTemplate = { url: file.getDownloadUrl() };

  let html = htmlTemplate
    .evaluate()
    .setWidth(400)
    .setHeight(300);

  SpreadsheetApp.getUi()
    .showModalDialog(html, 'download');
};

HTML
<input type="button" value="download" onclick="getUrl()" />
<script>
  function getUrl() {
    google.script.run.withSuccessHandler(download).getDownloadUrl();
  }

  function download(obj) {
    var d = document.createElement('a');
    d.href = obj.url;
    d.download = obj.filename;
    d.click();
  }
</script>

How to save these to an existing folder called TextFiles

Thanks

2 Answers 2

1

I believe your goal is as follows.

  • You want to create a text file to the specific folder by modifying your script.

In your situation, how about the following modification?

From:

let file = DriveApp.getRootFolder().createFile('Hi.txt', str);

To:

const folderName = "TextFiles"; // Please set the folder name you want to put the file.
const folders = DriveApp.getFoldersByName(folderName);
const folder = folders.hasNext() ? folders.next() : DriveApp.createFolder(folderName);
let file = folder.createFile('Hi.txt', str);
  • In this modification, when the folder of folderName is not existing, the folder of folderName is created as a new folder and put the file.

  • If the folder of folderName is existing in the Shared Drive, you can use the following script.

      const folderId = "###"; // Folder ID of the folder "TextFiles";
      const folder = DriveApp.getFolderById(folderId);
      let file = folder.createFile('Hi.txt', str);
    

References:

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

Drive.Files.update({"parents": [{"id": folder.getId()}]}, file.getId()); 

You must enable Drive API v2

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.