搜索文件夹以将已上传的文件移动到子文件夹 – Google表单

huangapple go评论62阅读模式
英文:

Search through a folder to move an uploaded file to a subfolder - Google forms

问题

我有一个谷歌表格,收集了一组个人的详细信息。他们选择了几个选项,最后上传了一个文件。我希望这些文件能够上传到谷歌驱动器中已经创建的特定文件夹(基于表格选择选项)。我在论坛中找到了一个很好的答案,但是对于子文件夹的搜索(在下面的参考链接中没有)对我来说有点模糊。

参考链接:
https://stackoverflow.com/questions/66436387/how-to-move-file-uploads-from-google-forms-to-a-specific-folder-subfolders-in/66456505#66456505?newreg=d619ac9e5f514c3eaa6a94a7e8ea2f93

例如:一个人填写了表格问题Q1:“1”,Q2:“form 1” <-上传。我在自定义的“reports”文件夹(在谷歌驱动器中)中放置了1、2和3文件夹。我希望这个特定的上传文件最终会放到“1”文件夹中。使用下面的代码,文件被上传到了其他文件夹,即Form uploads。

const PARENT_FOLDER_ID = "<文件夹ID>";

const initialize = () => {
  const form = FormApp.getActiveForm();
  ScriptApp.newTrigger("onFormSubmit").forForm(form).onFormSubmit().create();
};

const onFormSubmit = ({ response } = {}) => {
  try {
    // 获取一些有用的数据以创建子文件夹名称
    const answer = response.getItemResponses()[0].getResponse(); // 第一个答案中的文本
    
    // 获取与响应一起上传的所有文件的列表
    const files = response
      .getItemResponses()
      // 我们只关心“文件上传”类型的问题
      .filter(
        (itemResponse) =>
          itemResponse.getItem().getType().toString() === "FILE_UPLOAD"
      )
      .map((itemResponse) => itemResponse.getResponse())
      // 响应包括文件ID的数组,我们可以将其展开
      .reduce((a, b) => [...a, ...b], []);

    if (files.length > 0) {
      // 每个表单响应都有一个唯一的ID
      const parentFolder = DriveApp.getFolderById(PARENT_FOLDER_ID);
      const subfolder = parentFolder.getFoldersByName(answer).next(); // 我在这一步卡住了,我该如何搜索特定的文件夹并将文件放入其中?
      files.forEach((fileId) => {
        // 将每个文件移动到自定义文件夹中
        DriveApp.getFileById(fileId).moveTo(subfolder);
      });
    }
  } catch (f) {
    Logger.log(f);
  }
};
英文:

I have a google form that collects details of a set of individuals. They select several options and finally upload a file. I want these files to be uploaded to a specific folder (based on form selection options) that is already created in the google drive. I have found a very good answer in the forum, however, the search of the subfolder (not there is the below reference) is a bit cloudy to me.

Reference:
https://stackoverflow.com/questions/66436387/how-to-move-file-uploads-from-google-forms-to-a-specific-folder-subfolders-in/66456505#66456505?newreg=d619ac9e5f514c3eaa6a94a7e8ea2f93

Example: A person fills the form Q1. "1", Q2. "form 1" <- the upload. My other options for Q1 are 2 and 3. Inside my custom "reports" folder (in goolge drive) I have placed the 1,2 and 3 folders. I want this particular upload to end up in the "1" folder. With the below code, the file gets uploaded to some other folder, i.e., Form uploads.

const PARENT_FOLDER_ID = &quot;&lt;folder ID&gt;&quot;;

const initialize = () =&gt; {
  const form = FormApp.getActiveForm();
  ScriptApp.newTrigger(&quot;onFormSubmit&quot;).forForm(form).onFormSubmit().create();
};

const onFormSubmit = ({ response } = {}) =&gt; {
  try {
    // Get some useful data to create the subfolder name
    const answer = response.getItemResponses()[0].getResponse() // text in first answer
  
    // Get a list of all files uploaded with the response
    const files = response
      .getItemResponses()
      // We are only interested in File Upload type of questions
      .filter(
        (itemResponse) =&gt;
          itemResponse.getItem().getType().toString() === &quot;FILE_UPLOAD&quot;
      )
      .map((itemResponse) =&gt; itemResponse.getResponse())
      // The response includes the file ids in an array that we can flatten
      .reduce((a, b) =&gt; [...a, ...b], []);

    if (files.length &gt; 0) {
      // Each form response has a unique Id
      const parentFolder = DriveApp.getFolderById(PARENT_FOLDER_ID);
      const subfolder = parentFolder.getFoldersByName(answer).next(); //I am stuck at this point, how can I search for the particular folder and push the file inside
      files.forEach((fileId) =&gt; {
        // Move each file into the custom folder
        DriveApp.getFileById(fileId).moveTo(subfolder);
      });
    }
  } catch (f) {
    Logger.log(f);
  }
};

答案1

得分: 0

你有一个接受文件上传的 Google 表单。你打算表单上第一个问题的答案将决定用户文件的上传文件夹。你在 Google Drive 上创建了文件夹 "1"、"2"、"3" 来保存上传的文件。

  • 回答 1 的用户应将其文件上传放入名为 "1" 的文件夹中。
  • 回答 2 的用户应将其文件上传放入名为 "2" 的文件夹中。
  • 回答 3 的用户应将其文件上传放入名为 "3" 的文件夹中。

解决这个问题的方案是将电子表格与 Google 表单链接起来,接受表单提交的响应。电子表格将在每次表单提交时运行一个脚本;脚本将把文件上传移动到适当的文件夹。

安装:

  • 这些脚本绑定到电子表格。
  • 复制下面显示的所有代码并粘贴到项目编辑器中。
  • 找到这一行 const subfolderIDs = [&quot;&lt;&lt;folderID_1&gt;&gt;&quot;,&quot;&lt;&lt;folderID_2&gt;&gt;&quot;,&quot;&lt;&lt;folderID_3&gt;&gt;&quot;]
    • 用对应于每个文件夹 "1"、"2" 和 "3" 的 folderId 替换它。
  • 手动运行 createSpreadsheetOnFormSubmitTrigger()
    • 这样做一次(只能一次)。
    • 这将以程序方式创建 onFormSubmit 触发器。
英文:

You have a Google Form that accepts file uploads. You intend that the answer to Q#1 on the form will dictate the upload folder for the user file. You have created folders "1, "2","3" on Google Drive to hold uploads.

  • a user who answers 1, should have their file upload put in a folder name = "1"
  • a user who answers 2, should have their file upload put in a folder name = "2"
  • a user who answers 3, should have their file upload put in a folder name = "3"

The solution to this problem is a spreadsheet linked to the Google form and which accepts responses from Form submissions. The spreadsheet will run a script when each form submission is received; the script will move the file upload to the appropriate folder.


Installation:

  • These script are bound to the spreadsheet.
  • Copy ALL the code shown below and paste into the project editor
  • find this line const subfolderIDs = [&quot;&lt;&lt;folderID_1&gt;&gt;&quot;,&quot;&lt;&lt;folderID_2&gt;&gt;&quot;,&quot;&lt;&lt;folderID_3&gt;&gt;&quot;]
    • substitute the folderId for each of folders "1", "2" and "3".
  • Manually run createSpreadsheetOnFormSubmitTrigger()
    • do this once (and only once).
    • This will programmatically create the onFormSubmit trigger

// create a trigger that will fire when the spreadsheet has a form submitted to it.
function createSpreadsheetOnFormSubmitTrigger(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  ScriptApp.newTrigger(&quot;moveFileSubmission&quot;)
    .forSpreadsheet(ss)
    .onFormSubmit()
    .create();
}

function moveFileSubmission(e){
  // these are the sub-folders in the UPLOAD FOLDER that relate to the answers to Q1
  const subfolderIDs = [&quot;1S0x9KcR1VgD00Op_G_lV9EnGwRmMuL2P&quot;,&quot;1VWae65JeDNbXgraIloPh-h9q2CVLXvD4&quot;,&quot;1m7CcLYcaGOtH_ojMR2RKEWqxEzt7L0Qi&quot;]

  // get Event Objects and values 
  var response = e.values;
  // answer to Question 1
  var question1 = response[1]
  // the file url of the upload
  var fileUrl = response[2]

  // get the fileId from the fileUrl
  var fileId = getIdFromUrl(fileUrl)
  // Logger.log(&quot;DEBUG: question#1 answer = &quot;+question1+&quot;, URL = &quot;+fileUrl+&quot;, fileID = &quot;+fileId)

  // get the subfolderID based on the answer to qn#1
  var subfolderID = subfolderIDs[(question1-1)]
  // Logger.log(&quot;DEBUG: the subfolder id = &quot;+subfolderID)

  // get the subfolder
  var subfolder = DriveApp.getFolderById(subfolderID)

  // Move the uploaded file into the appropriate folder
  DriveApp.getFileById(fileId).moveTo(subfolder)
}


//Easiest way to get file ID from URL on Google Apps Script
// https://stackoverflow.com/a/16840612/1330560
function getIdFromUrl(url) { 
  return url.match(/[-\w]{25,}/); 
}

LOGIC

  • const subfolderIDs - the target folderIds are in an array (zero-based). This makes it easy to take the answer to question#1 and select the appropriate folderId.
  • var response = e.values;- the solution makes use of Event Objects
  • var question1 = response[1] & var subfolderID = subfolderIDs[(question1-1)]
    • get answer to question#1,
    • subtract 1 (for the zero-based array),
    • get that value from the array of subfolderIDs.
  • var fileUrl = response[2] - the url of the uploaded file is included in the Event Objects BUT there's currently no way to get a file by URL. So we need to use a utility getIdFromUrl() to extract the FileID from the URL.
  • var subfolder = DriveApp.getFolderById(subfolderID) - gets the destination folder.
  • DriveApp.getFileById(fileId).moveTo(subfolder) - moves the file to the appropriate folder.

Comments on the OP's referenced script

The OP included a script from How to Move File Uploads from Google Forms to a Specific Folder & Subfolders in Google Drive. Though it appeared similar to the OP's scenario, it was actually quite different.

  • involved multiple uploads per user
  • required a unique upload folder for EVERY user.
  • got file details via the form rather than the spreadsheet.

huangapple
  • 本文由 发表于 2023年5月7日 16:25:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76192872.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定