Google脚本会继续将文件上传到相同文件夹

时间:2016-03-02 10:39:31

标签: google-apps-script google-drive-api

我有两个文件:code.gs和form.html。我在code.gs中更改文件夹名称,但仍然在相同的文件夹中上传,即学生档案。

form.html

<form id="myForm">
    <input type="text" name="myName" placeholder="Your name..">
    <input type="file" name="myFile">
    <input type="submit" value="Upload File" 
           onclick="this.value='Uploading..';
                    google.script.run.withSuccessHandler(fileUploaded)
                    .uploadFiles(this.parentNode);
                    return false;">
</form>

<div id="output"></div>

<script>
    function fileUploaded(status) {
        document.getElementById('myForm').style.display = 'none';
        document.getElementById('output').innerHTML = status;
    }
</script>

<style>
 input { display:block; margin: 20px; }
</style>

code.gs

function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('form.html');
}

function uploadFiles(form) {

  try {   

    var folderName = "Test";
    var exist = true;
    try {
      var folderName = DocsList.getFolder(folderName)
      }

    catch(err) {
      exist=false
    }

    if (exist) {
      folder = folderName;
    } else {
      folder = DriveApp.createFolder(folderName);
    }

    var blob = form.myFile;
    var file = folder.createFile(blob);    
    file.setDescription("Uploaded by " + form.myName);=
    return "File uploaded successfully " + file.getUrl();
  } catch (error) {
    return error.toString();
  }

}

code.gs文件由变量folderName组成。

检查此名称,如果此名称的文件夹存在,则会创建一个新文件夹。但是这里没有创建新文件夹。而是将文件上传到同一文件夹,即学生档案。

2 个答案:

答案 0 :(得分:2)

上一个答案只是问题代码的副本。

DocsList.getFolder(folderName)函数可能没有获取任何文件夹,这就是为什么文件会在以前的文件夹中上传。

答案 1 :(得分:0)

更改您的code.gs

function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('form.html');
}

function uploadFiles(form) {

  try {   

    var folderName = "Test";
    var exist = true;
    try {
      var folderName = DriveApp.getFoldersByName(folderName)
      }

    catch(err) {
      exist=false
    }

    if (exist) {
      folder = folderName;
    } else {
      folder = DriveApp.createFolder(folderName);
    }

    var blob = form.myFile;
    var file = folder.createFile(blob);    
    file.setDescription("Uploaded by " + form.myName);=
    return "File uploaded successfully " + file.getUrl();
  } catch (error) {
    return error.toString();
  }

}